If you have ever built a to-do list, a comment section, or a product grid, you have probably written a loop that adds a click listener to every single button. It works — until the list grows, or new items get added later and their buttons do nothing. Event delegation fixes both problems with one listener.
The idea is simple. Events in JavaScript bubble up. When you click a button inside a list, the click event travels up through the list, the container, and the body. So instead of listening on every button, you listen once on the parent and check which child was actually clicked.
// The slow way: one listener per button
document.querySelectorAll('.delete-btn').forEach(btn => {
btn.addEventListener('click', () => btn.closest('li').remove());
});
// The delegation way: one listener on the parent
document.querySelector('#todo-list').addEventListener('click', (event) => {
if (event.target.matches('.delete-btn')) {
event.target.closest('li').remove();
}
});
The second version has three advantages. First, it uses less memory — one listener instead of hundreds. Second, it works for elements added later, because the parent was already listening when they arrived. Third, your code is shorter and easier to maintain.
The pattern is always the same: attach the listener to a stable parent, use event.target to find what was clicked, and use matches() or closest() to confirm it is the element you care about. This is how most real apps handle lists, tables, and menus.
One common mistake is listening too high up, like on document, for everything. That works, but it makes debugging harder. Listen on the closest stable parent instead — the list itself, not the whole page.
Event delegation is one of those small ideas that changes how you write JavaScript. Learn it once, and you will use it in almost every project.
Top comments (0)