Learn the concept
Events
Event delegation is a pattern where you attach a single event listener to a parent element instead of individual listeners on each child. It works because events bubble up through the DOM, and you can check event.target to determine which child was clicked.
Event delegation leverages event bubbling — when an event occurs on an element, it bubbles up through all its ancestors.
How it works:
event.target to identify which child element was actually clickedBenefits:
When to use:
// ❌ Without delegation — listener on every item
const items = document.querySelectorAll('li');
items.forEach(item => {
item.addEventListener('click', (e) => {
console.log(e.target.textContent);
});
});
// ✅ With delegation — one listener on parent
const list = document.querySelector('ul');
list.addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
console.log(e.target.textContent);
}
});
// New items added later automatically work!
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
list.appendChild(newItem); // clicking this will trigger the handlerManaging click handlers on todo lists, comment threads, or feeds where items are frequently added and removed
Using a single scroll handler on a container element for dynamically loaded content
Handling events on form inputs that are added or removed dynamically without re-attaching listeners
Build a todo app using a single event listener on the parent <ul> to handle all item interactions
Build a sortable and filterable table using event delegation for column headers and row actions