Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda