Event delegation is a technique where instead of adding event listeners to multiple child elements, you add a single event listener to their parent and let the event bubble up to handle it.
This works because events in the DOM naturally bubble from the target element up through its ancestors.
🧾 Example:
document.getElementById('list').addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
console.log('Clicked:', e.target.textContent);
}
});
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
👉 Here, instead of adding a click listener to every <li>, we added one to the <ul> and used e.target to detect which item was clicked.
✅ Why it’s useful:
- Improves performance in large DOM trees (fewer event listeners).
- Makes the code cleaner and easier to maintain.
- Works well with dynamically added elements (no need to reattach listeners).