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

221
Vistas
Adding Event Listeners to divs works with ForEach() method, but doesn't work with for loop. What's the difference?

As in title. I'm trying to add an event listener to all available divs that outputs their ID on click, but it works only with forEach method. For loop ends up only outputting the ID of my last div, even if I click the other ones.

This is the part of code that works properly:

const elements = document.querySelectorAll('div')

elements.forEach(element => {
            element.addEventListener('click', ()=>{
            console.log(element.id)

})
        })

And this doesn't, it always outputs id10 in console (my last added div):

const elements = document.querySelectorAll('div')

for(element of elements){
            element.addEventListener('click', ()=>{
            console.log(element.id)
        })}

Shouldn't these two work exactly the same? What's the difference? Is there a way to make the for loop work?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The difference is how you have implemented your code. In the forEach method, you have declared elements to be global. Use let in forEach. Example code:

for(let element of elements){
            element.addEventListener('click', ()=>{
            console.log(element.id)
        })}

This will return the element id of each clicked element.

If you use your implementation without let, then it will point to the last div element

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