Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!