Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Generally you do it the "document" way (often called a "delegated" listener) when you have lots of elements you want to listen to, or particularly elements that will be dynamically added and removed.

If you listen directly to every target element, you have to find the elements and loop through them all, they have to exist at the time you set the listener, and you have to make sure to add the listener every time you add a new element that has the same behavior. If you listen at the document (or some appropriate parent element) and then check if the element that fired the event matches what you're trying to handle, you can have one listener that will apply to all the matching children regardless of where/when/how they're added.



Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: