Skip to content

With Delegation

Event delegation attaches a single listener to a parent element and uses the event’s target to determine which child was interacted with.

// ✅ Single listener on parent
document.querySelector('ul').addEventListener('click', (e) => {
const item = e.target.closest('li');
if (item) {
console.log('Item clicked:', item.textContent);
}
});
// Works for all items — existing and future!
flowchart LR
subgraph "With Delegation ✅"
C["<ul> (1 listener)"]
D["1000 list items"]
E["Event bubbles up to <ul>"]
end
C --> D
D --> E
  • ✅ Single listener vs thousands — less memory
  • ✅ Works for dynamically added elements
  • ✅ Easier to maintain and update
  • ✅ Better performance
  • One parent listener handles all children via event bubbling
  • Use e.target.closest() to identify the specific target
  • Works for dynamically added elements
  • Reduces memory usage and improves performance