Home > database >  Adding Event Listeners to divs works with ForEach() method, but doesn't work with for loop. Wha
Adding Event Listeners to divs works with ForEach() method, but doesn't work with for loop. Wha

Time:12-27

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?

CodePudding user response:

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

  • Related