Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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!");
  }
});
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

const collection = document.getElementsByClassName("classname");

getElementsByClassName method returns 'an array' ("a live HTMLCollection, which is very similar to an array" - user1599011) . You can iterate thru it like

foreach (element in array) {
Do anything with element} 
about 4 years ago · Santiago Trujillo Relatório

0

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>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda