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

106
Visualizações
How can I handle multiple button?

I want to handle multiple buttons. My aim is when a user will click on the first button then the first paragraph will be changed, again when a user will click on the second button then the second paragraph will be changed. I tried, but not working. Please check my code and give me a solution....

var len = document.querySelectorAll(".myButton").length
var plen = document.querySelectorAll(".myP").length
for (i = 0; i < len; i++) {
  for (j = 0; j < plen; j++) {
    document.querySelectorAll(".myButton")[i].addEventListener("click", function() {
      if (document.querySelectorAll(".myButton")[i] == document.querySelectorAll(".myP")[j]) {
        document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;
      }
    });
  }
}
<p class="myP">oke</p>
<p class="myP">oke</p>

<h1 class="pt-3 pb-3 pl-5 pr-5 bg-warning text-light btn mx-5 my-5">00</h1><br>
<hr style="background-color:red; width:50%">
<button class="btn bg-primary text-light mx-5 my-5 myButton">one</button>
<button class="btn bg-primary text-light mx-5 my-5 myButton">two</button>

error:

5_eventListener.html:43 Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')
    at HTMLButtonElement.<anonymous> (5_eventListener.html:43:119)

Error line:

document.querySelectorAll(".myP")[j].innerHTML = document.querySelectorAll(".myButton")[i].innerHTML;
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your code needs closures to work and that is quite tricky

Instead delegate - here I delegate from document, but if the buttons have a wrapper, you can delegate from that

Much simpler. Also use data attributes to give a target to the buttons

document.addEventListener("click", function(e) {
  const tgt = e.target;
  if (!tgt.matches(".myButton")) return 
  document.getElementById(tgt.dataset.target).innerHTML = tgt.innerHTML;
})  
<p class="myP" id="p1">oke</p>
<p class="myP" id="p2">oke</p>

<h1 class="pt-3 pb-3 pl-5 pr-5 bg-warning text-light btn mx-5 my-5">00</h1><br>
<hr style="background-color:red; width:50%">

<button class="btn bg-primary text-light mx-5 my-5 myButton" data-target="p1">one</button>
<button class="btn bg-primary text-light mx-5 my-5 myButton" data-target="p2">two</button>

about 4 years ago · Santiago Trujillo Relatório

0

I dont understand why you will need such a thing - but, here go - a version real close to @mplungjan which is correct, i just don't think you should listen to a click on the entire document, also made it more readable for beginners i hope

Live example:
https://jsfiddle.net/dm3bwzgr/

<p id="p1">text 1</p>
<p id="p2">text 2</p>

<button class="btn" data-target="p1">Button 1</button>
<button class="btn" data-target="p2">Button 2</button>

<script>
// listen to click event on all buttons
document.querySelectorAll('.btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var target = btn.dataset.target
        var el = document.getElementById(target)
              
        // apply button text to target element
        el.innerHTML = btn.innerHTML;
    });
});
</script>
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