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

112
Views
JavaScript - For loop within a for loop triggering twice on button press

I have a series of horizontal lists within one vertical list. Each list item has an ID 'cr-id-x_y' where x is the vertical list item index and y is the horizontal list item index. I have created a for loop within a for loop to determine which list item has been targeted. The problem I'm having is the button presses seem to be firing twice (i.e. I'm seeing "Hello world" printed to the console twice on a button press). Please can someone tell me where I'm going wrong?

document.getElementById("parent-list").addEventListener("click", function (e) {
  for (let x = 0; x < 100; x++) {
    for (let i = 0; i < 30; i++) {
      if (
        e.target.closest(`#cr-id-${x}_${i}`) &&
        (e.target.nodeName == "BUTTON" ||
          e.target.parentElement.nodeName == "BUTTON")
      ) {
        console.log("Hello world");
      }
    }
  }
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

From the code you posted, it is not possible to guess why it is firing twice, but actually there is no need to loop at all. When you delegate like you do, you should be able to interrogate the clicked target - for example like this

document.getElementById("parent-list").addEventListener("click", function(e) {
  const tgt = e.target; // or if nested e.target.closest('button'), then use tgt in the next if
  if (tgt.tagName==="BUTTON") {
    const someParent = tgt.closest('someElementThatMightHaveCRId');
    if(someParent.id && someParent.id.startsWith('cr-id-')) {                
      console.log("Hello world",someParent.id);
    }
  }
})
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!