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

120
Vistas
JavaScript - For loop within a for loop triggering twice on button press

I have a series of horizontal lists within one vertical list. Each list item has an ID 'cr-id-x_y' where x is the vertical list item index and y is the horizontal list item index. I have created a for loop within a for loop to determine which list item has been targeted. The problem I'm having is the button presses seem to be firing twice (i.e. I'm seeing "Hello world" printed to the console twice on a button press). Please can someone tell me where I'm going wrong?

document.getElementById("parent-list").addEventListener("click", function (e) {
  for (let x = 0; x < 100; x++) {
    for (let i = 0; i < 30; i++) {
      if (
        e.target.closest(`#cr-id-${x}_${i}`) &&
        (e.target.nodeName == "BUTTON" ||
          e.target.parentElement.nodeName == "BUTTON")
      ) {
        console.log("Hello world");
      }
    }
  }
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

From the code you posted, it is not possible to guess why it is firing twice, but actually there is no need to loop at all. When you delegate like you do, you should be able to interrogate the clicked target - for example like this

document.getElementById("parent-list").addEventListener("click", function(e) {
  const tgt = e.target; // or if nested e.target.closest('button'), then use tgt in the next if
  if (tgt.tagName==="BUTTON") {
    const someParent = tgt.closest('someElementThatMightHaveCRId');
    if(someParent.id && someParent.id.startsWith('cr-id-')) {                
      console.log("Hello world",someParent.id);
    }
  }
})
about 4 years ago · Juan Pablo Isaza 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