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

222
Visualizações
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 Respostas
Responde à pergunta

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 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