Event delegation is a JavaScript technique where you attach a single event listener to a parent element instead of adding listeners to multiple child elements individually.
It works because of event bubbling — when an event (like a click) occurs, it bubbles up the DOM tree from the target element to its ancestors.
1️⃣ How It Works
Instead of adding a click listener to every child element, you add one listener to the parent, and check which child triggered it.
document.getElementById("list").addEventListener("click", function (e) {
if (e.target.tagName === "LI") {
console.log("You clicked:", e.target.textContent);
}
});
<ul id="list">
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
✅ When any <li> is clicked, the event bubbles up to <ul>, where it’s handled.
2️⃣ Why It’s Useful
- Performance Efficient:
Only one event listener instead of one per child element. - Handles Dynamic Elements:
Works even for new child elements added later. - Cleaner Code:
Simplifies event handling in lists, tables, or grids.
3️⃣ Example with Dynamic Elements
const list = document.getElementById("list");
list.addEventListener("click", (e) => {
if (e.target.matches("li")) {
alert(`You clicked ${e.target.textContent}`);
}
});
const newItem = document.createElement("li");
newItem.textContent = "Mango";
list.appendChild(newItem); // Works without extra listener!
💡 In Short:
Event delegation lets you handle events for multiple or dynamic child elements efficiently by using one listener on a common parent, leveraging event bubbling.