skip to Main Content

How do I add event listeners on click to the edit button and make them edit different sections if the classes and HTML code is the same for all edit buttons

<div className="top-row">
  <div className="left-header">ABOUT ME</div>
  <div className="right-header">Edit</div>
</div>
<div className="bottom-row">

...

<div className="top-row">
  <div className="left-header">PLEASE UPDATE YOUR LINKS</div>
  <div className="right-header">Edit</div>
</div>
<div className="bottom-row">

Screen layout for reference
enter image description here

getElementByClassName() does not seem to work

4

Answers


  1. I resolved this in codesandbox.

    https://codesandbox.io/s/boring-edison-hii8rb?file=/index.html

    you can use querySelectorAll to catch all elements if this class, and use forEach to iterate them.

    I found an error, you use class as className, this is used in React, in HTML we use only class, because this you can’t get with getElementsByClassName function.

    <div class="top-row">
      <div class="left-header">ABOUT ME</div>
      <div class="right-header">Edit</div>
    </div>
    <div />
    
    <div class="top-row">
      <div class="left-header">PLEASE UPDATE YOUR LINKS</div>
      <div class="right-header">Edit</div>
    </div>
    <div />
    
    <script>
      const editBtn = document.querySelectorAll(".right-header");
      editBtn.forEach((element) => {
        console.log(element);
      });
    </script>
    
    Login or Signup to reply.
  2. Your question is a bit confusing, because you’re asking for help re-creating the functionality of a site based on its HTML, but you tagged this question with React, so if you’re just using HTML to code this site, then @JoSSte is right, you can just use unique ids to select the elements in question. You could also use getElementsByClassName and write individual addEventListener callbacks for each item in the resultant array. That would look something like this:

    let editButtons = document.getElementsByClassName("right-header");
    
    editButtons[0].addEventListener("click", (event) => {Enter function here});
    

    If you’re looking to execute different actions for each Edit button using React, but the site that you’re trying to clone isn’t utilizing unique ids for each one, then it’s likely they’re probably using props to pass the information for each action into a component that’s being called multiple times.

    For example, you could do something like this in your components:

    //INSIDE PARENT COMPONENT: 
    
      const editAboutMe = () => {
       { Desired functionality here }
      }    
    
      return (
        <>
          <MenuItem title="ABOUT ME" edit={editAboutMe}/>
        </>
      ) 
    
    //INSIDE CHILD COMPONENT:
      
      return (
        <>
          <div>{title}<div>
          <div onClick={edit}>EDIT</div>
        </>
      )
    

    Code is a bit choppy, but hopefully that helps!

    Login or Signup to reply.
  3. You’d need to use a selector that is position based to qualify it.

    Also, your HTML is incorrect, you should be using class not className. className is used in JavaScript to access a list of all the classes applied to an element. In HTML, you just use the class attribute.

    See comments below:

    // Set up a single event handler on a common ancestor of 
    // the elements you wish to handle
    document.querySelector(".wrapper").addEventListener("click", function (event){
      // Determine if the event originated at an element you care about
      if(event.target.classList.contains("right-header")){
        // Handle the event based on the text of the
        // clicked element's immediate previous element sibling
        switch (event.target.closest("div.top-row").querySelector("div.left-header").textContent.toLowerCase()) {
            case "about me":
              console.log("You clicked the About Me edit.");
              break;
            case "email":
              console.log("You clicked the Email edit.");
              break;
            case "links":
              console.log("You clicked the Links edit.");
              break;
         }
      }
    });
    .right-header {
      background-color:#e0e0e0;
      padding:5px;
      border:1px solid #808080;
      display:inline-block;
      cursor:pointer;
    }
    <div class="wrapper">
      <div class="top-row">
        <div class="left-header">ABOUT ME</div>
        <div class="right-header">Edit</div>
      </div>
      <div class="top-row">
        <div class="left-header">EMAIL</div>
        <div class="right-header">Edit</div>
      </div>
      <div class="top-row">
        <div class="left-header">LINKS</div>
        <div class="right-header">Edit</div>
      </div>
    </div>
    Login or Signup to reply.
  4. A number of ways to do this based on element classes, position of the type, based on data attributes etc.

    Here are a few examples.

    function editLinks(event) {
      console.log("Get that link edited!");
    }
    
    function editAbout(event) {
      console.log("Edit About!");
    }
    
    function lastHandler(event) {
      console.log("lastHandler woot!");
    }
    
    function clickAnotherEventHander(event) {
      console.clear();
      console.log(`We have to: ${this.dataset.type} `);
    }
    
    function clickEventHander(event) {
      const action = event.target.dataset.eventAction;
      switch (action) {
        case 'editLinks':
          editLinks(event)
          break;
        case 'editAbout':
          editAbout(event)
          break;
        default:
          console.log(`Sorry, we are out of ${action}.`);
      }
    }
    const edits = document.querySelector('.container-a').querySelectorAll('.right-header');
    edits.forEach(edt => {
      edt.addEventListener('click', clickEventHander, false);
    });
    
    const nextup = document.querySelector('.container-b')
      .querySelectorAll('[data-event-action="another"]');
    nextup.forEach(edt => {
      edt.addEventListener('click', clickAnotherEventHander, false);
    });
    
    const lastly = document.querySelector('.container-b')
      .querySelectorAll('.right-header:nth-last-of-type(1)');
    lastly.forEach(edt => {
      console.log('geter done');
      edt.addEventListener('click', lastHandler, false);
    });
    body {
      font-size: 16px;
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      display: grid;
      place-items: center;
      gap: 1rem;
    }
    
    .container {
      display: grid;
      border: double #00FF00 3px;
    }
    
    .right-header {
      border-radius: 1rem;
      background-color: #FFA500;
      width: 5rem;
      text-align: center;
      padding: 0.25rem;
    }
    
    .a-row {
      border: solid 1px #0000FF;
      padding: 1rem;
    }
    <div class="container container-a">
      <div class="a-row top-row">
        <div class="left-header">ABOUT ME</div>
        <div class="right-header" data-event-action="editLinks">Edit</div>
      </div>
      <div class="a-row">
        <div class="left-header">Send Freddy home</div>
        <div class="right-header" data-event-action="sendFreddy">Edit</div>
      </div>
      <div class="a-row">
        <div class="left-header">Fish for dinner</div>
        <div class="right-header" data-event-action="fish">Edit</div>
      </div>
      <div class="a-row bottom-row">
        <div class="left-header">PLEASE UPDATE YOUR LINKS</div>
        <div class="right-header" data-event-action="editAbout">Edit</div>
      </div>
    </div>
    <div class="container container-b">
      <div class="a-row top-row">
        <div class="left-header">ABOUT ME</div>
        <div class="right-header" data-event-action="another" data-type="Get beer!">Edit</div>
      </div>
      <div class="a-row">
        <div class="left-header">What? Click and see!</div>
        <div class="right-header" data-event-action="another" data-type="walleye">Edit</div>
      </div>
      <div class="a-row">
        <div class="left-header">Fish for dinner</div>
        <div class="right-header" data-event-action="another" data-type="bass">Edit</div>
      </div>
      <div class="a-row bottom-row">
        <div class="left-header">I do nothing!</div>
        <div class="right-header" data-event-action="whocares">Edit</div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search