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

181
Views
How to make event listener to keep working after elements are added to the DOM (pure js)

I have this listener:

//close all detail tags when click happens outside
document.addEventListener('click', function(e) {
 if (!details.some(f => f.contains(e.target))) {
   details.forEach(f => f.removeAttribute('open'));
 } else {
   details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
 }
})

it automatically closes all the open details tags when a new one is clicked or you click anywhere on the page, that works fine. Problems arise when a new detail tag will be added dynamically then the listener wont work for them. I was reading other questions related and most suggested delegation but this doesnt seem to be the case because the listener should work for both normal tags and dynamic tags as well.

I tried some suggestions like this:

document.addEventListener('click', function(e){
    if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
         //my code
    }
});

but no change. You can test it here https://jsfiddle.net/nxv03wjo/ and here https://jsfiddle.net/nxv03wjo/1/

What's the trick here?

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

0

Just retrieve the details elements inside the click listener?

document.addEventListener('click', function (e) {
    const details = [...document.querySelectorAll('details')];
    if (!details.some(f => f.contains(e.target))) {
        details.forEach(f => f.removeAttribute('open'));
    } else {
        details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
    }
});
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!