JavaScriptEasy
What is event delegation?
By FrontendPro Editorial Team Updated 9/26/2026
#JavaScript
Answer
Event delegation means attaching one listener to a common ancestor instead of one listener per child, and working out which child was clicked from event.target. It works because events bubble: a click on a <li> also reaches the <ul> above it.
js
document.querySelector("#todos").addEventListener("click", (e) => {
const item = e.target.closest("[data-id]");
if (!item) return; // clicked padding or the container itself
toggleDone(item.dataset.id);
});
Why bother
- One listener instead of hundreds. Less memory, and no loop to wire things up.
- Works for elements that do not exist yet. Add a row after the page loaded and it is handled with no extra code — this is usually the real reason to reach for it.
- Nothing to clean up when rows are removed, so no leaked listeners.
What to watch out for
e.targetis the deepest element hit, which may be an icon inside the button.closest()walks back up to the element you actually care about.- Some events do not bubble, so they cannot be delegated:
focus,blur,scroll,mouseenter,mouseleave. Usefocusin/focusoutfor the first two. - Guard against clicks that land on the container itself, otherwise
closest()returnsnulland you get a crash on the next line. - The handler runs for every click inside the container, so keep the early exit cheap.
