Event Delegation
Event delegation leverages event bubbling to handle events on many children with a single listener on a parent. It is memory-efficient, works for dynamically added elements, and is the backbone of modern list UIs.
What is event delegation in JavaScript?
Event delegation means attaching one listener to a parent element instead of one to every child, and using event.target.closest(selector) to find which child was clicked. Because events bubble up, this works for many items and for items added later, with less memory and less setup code.
document.querySelector("#todo-list").addEventListener("click", (e) => {
const button = e.target.closest("button.delete");
if (!button) return;
button.closest("li").remove();
});How It Works
- 1User clicks on a child element (e.g., a <li>)
- 2The click event bubbles up through the DOM tree
- 3The parent listener receives the event
- 4event.target points to the original clicked element
- 5Use target.matches() or target.closest() to act
Benefits at a Glance
Delegation Patterns
matches() guard
list.addEventListener('click', (e) => {
if (!e.target.matches('li')) return;
// handle <li> clicks
});closest() for nested
list.addEventListener('click', (e) => {
const item = e.target.closest('li');
if (!item) return;
// handles clicks on <li> or any child
});data-action dispatch
parent.addEventListener('click', (e) => {
const btn = e.target.closest('[data-action]');
if (!btn) return;
actions[btn.dataset.action]?.(btn.dataset.id);
});Generic delegate()
function delegate(parent, sel, type, fn) {
parent.addEventListener(type, (e) => {
const t = e.target.closest(sel);
if (t && parent.contains(t)) fn(e, t);
});
}Common Pitfalls
Interactive Delegation Demo
Code Editor
<ul id="list">
<li>Learn HTML <button class="del">✕</button></li>
<li>Learn CSS <button class="del">✕</button></li>
</ul>
<button id="add">Add item</button>Preview
Event delegation — step by step
The bubbling mechanism that makes delegation work
DOM events bubble up from the target element through all ancestors to the document root. A click on a button inside a li inside a ul bubbles: button → li → ul → div → body → html → document. Attaching a listener to the ul means it catches clicks from any descendant, including elements added dynamically after the listener was set up.
🎯 Quick Check
You have a ul with 500 li items generated dynamically. What is the best event listening strategy?
Event Delegation: summary
Key points
closest()handles clicks on nested elements, such as an icon inside the button.- Delegation works for any event that bubbles:
click,input,keydown,submit. focusandblurdon't bubble; usefocusinandfocusoutinstead.
Frequently asked questions
›Why use event delegation?
One listener instead of hundreds, and elements added dynamically are handled automatically without attaching new listeners.