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

153
Views
event.addEventListener() in forEach loop
function initNumberElement(){
let idReference = ['zero','one','two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
let numberElementReference = [];
let temp = '0';

for (const key of idReference) {
    numberElementReference.push(document.getElementById(key));
    for (let i = 0; i < numberElementReference.length; i++) {
        numberElementReference[i].addEventListener('click', () => {
            temp = temp + String(i);
            changeVisualOut(temp)
        })
    }
}
return numberElementReference;

}

Once the elements have been retrieved from the Dom I am trying to dynamically insert an addEventListener () for each element with forEach () but every time I click on an element the event is triggered several times. Why?

Even using a for loop the dynamics remain the same

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You dont need second loop at all. In first loop you are iterating through id list and add elements into numberElementReference array. Then for all elements in numberElementReference array you are adding click handler, thats why you got multiple listeners per element (because for each item in outer loop you are registering event listeners for the whole numberElementReference array again)

You can just use one loop:

function initNumberElement() {
  let idReference = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
  let numberElementReference = [];
  let temp = "0";

  for (let i = 0; i < idReference.length; i++) {
    const id = idReference[i];
    const element = document.getElementById(id);

    numberElementReference.push(element);

    element.addEventListener("click", () => {
      temp = temp + String(i);
      changeVisualOut(temp);
    });

  }

  return numberElementReference;

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