Search code examples
javascriptgoogle-chrome-extension

How to Target multiple buttons with same class_Name such as 15 buttons in java_script


my concern is there is a list and every list item has a button in front of them so i have to perform some action when user click on the button ,so how can i target the multiple buttons with same class_Name in java_script, Here is my j_s code =

function getActiveCampaigns() {
  fetch('http://example/api/sign/in', {
    method: 'GET',
    headers: {
      token: "token"
    }
  }).then(
    res => {
      res.json().then(
        data => {
          console.log(data.response.campaign, 'campaign');
          if (data.response.campaign.length > 0) {

            let temp = "";
            data.response.campaign.forEach((itemData) => {
              temp += "<ul>";
              temp += "<li>" + itemData.name + "</li>";
              temp += '<li><button class="btn1">Add to campaigns</button></li></ul>'
            });
            document.getElementById("ds").innerHTML = temp;
          }
        }
      )
    }
  )
}

 

   this code is that i have been tried but did not worked=
   

 
$("btn1").each(function click1(index, element) {
  var clas = $(element).attr("class");
  if(clas.length > 2) {
     // do something
     console.log("Hello World!");
  }
});

Solution

  • A single click event listener can handle 1, 10, or 1,000 buttons with ease.

    In my snippet, most of the code is concerned with creating and displaying 20 li elements, each with a button and some text.

    A single click event listener handles clicks on any of the buttons. I've used an AND conditional to process the subset of events that occur on a button AND that are in a li of the correct class name (incase you have multiple lists and want to do different things on each. This is the event listener:

        document.addEventListener('click', event => {
    
          if (event.target.tagName == 'BUTTON' && event.target.parentElement.className == 'list-item') { 
           // stuff to execute
           alert(`${event.target.innerHTML} button pressed`);  
          } // end if;
    
        }); // end event listener;
    
    

    Any number of if blocks could be added to the same event listener to deal with any other parts of the page for which you wish to process click events.

    Note, no ids or anything complicated was needed to distinguish the target from others (that is the job of the lisener). This example didn't even need a class attribute but I included it so you can see how extra specificty can be achieved (e.g. you might have two lists with buttons and want to do different things with them).

    Here is the working snippet:

    let list = document.getElementsByTagName('ul')[0];
    
    for (let i=0; i<20; i++) {
    let listItem = document.createElement('li');
    listItem.setAttribute("class", "list-item");
    listItem.innerHTML = `<button>element ${i}</button> list item ${i}`;
    list.appendChild(listItem);
    } // next.
    
    document.addEventListener('click', event => {
    
      if (event.target.tagName == 'BUTTON' && event.target.parentElement.className == 'list-item') { 
       // stuff to execute
       alert(`${event.target.innerHTML} button pressed`);  
      }
    
    });
    <ul>
    </ul>