Event delegation is a JavaScript technique where you attach a single event listener to a parent element instead of adding listeners to each child element individually.
The event then bubbles up from the child to the parent, and the parent handles it.
🔍 How It Works (Simple Explanation)
- Events like
clickbubble from the target element → up to its ancestors. - You add ONE listener on the parent.
- Inside the listener, you check which child triggered the event using
event.target.
🧪 Example: Without Event Delegation
You want to handle clicks on list items:
document.querySelectorAll("li").forEach(li => {
li.addEventListener("click", () => console.log("clicked"));
});
❌ Problem:
- Too many listeners
- Bad performance for large lists
- Newly added
<li>won't work automatically
🧪 Example: With Event Delegation (Better)
document.querySelector("ul").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log("Clicked:", e.target.textContent);
}
});
✔ Only one listener
✔ Works for dynamically added <li>
✔ Better performance
🎯 When Is Event Delegation Useful?
✔ 1. Lists with many items (menus, comments, products, chat messages)
You avoid creating 100s of listeners.
✔ 2. Dynamic elements added later via JavaScript or React
Works automatically without adding new listeners.
✔ 3. Improving performance in large DOM trees
Less memory usage.
✔ 4. Handling events on table rows, dropdowns, modals, forms, etc.
One listener manages all children.
⭐ Short Interview Answer
Event delegation is attaching a single event listener to a parent element instead of multiple listeners on child elements.
It works because events bubble up the DOM.
It is useful for dynamic elements, better performance, and avoiding multiple event listeners.