Hiprup

What is event delegation?

Event delegation is a pattern where you attach a single listener to a common parent instead of one listener on every child. It relies on event bubbling.

When an event fires on a child, it bubbles up to the parent, whose handler inspects event.target to decide how to respond.

Benefits:

  • Performance — one listener instead of hundreds saves memory and setup.

  • Dynamic content — newly added children work automatically, with no need to re-bind.

  • Simpler teardown — removing the parent removes the handler.

Key methods: use event.target to find what was clicked, and closest() to match the right container.

// Without delegation (bad for dynamic lists)
document.querySelectorAll('.item').forEach(item => {
  item.addEventListener('click', handleClick); // One listener per item!
});
// New items added dynamically won't have listeners!

// With delegation (one listener handles all)
document.getElementById('list').addEventListener('click', (event) => {
  const target = event.target;
  
  if (target.matches('.delete-btn')) {
    deleteItem(target.closest('.item').dataset.id);
  }
  
  if (target.matches('.edit-btn')) {
    editItem(target.closest('.item').dataset.id);
  }
});

// Works for dynamically added items!
function addItem(name) {
  const li = document.createElement('li');
  li.className = 'item';
  li.innerHTML = `${name} <button class="delete-btn">Delete</button>`;
  document.getElementById('list').appendChild(li);
  // No need to attach a new listener!
}

// Event phases
// Capturing: window → document → html → body → parent → target
// Bubbling:  target → parent → body → html → document → window

One listener on #list handles all clicks within it. event.target identifies the actual clicked element. matches('.delete-btn') checks if the target is a delete button. closest('.item') finds the parent item element. New items added dynamically are automatically handled because the listener is on the parent, not the children.

Event delegation is one of the most asked DOM questions. Show the problem (many listeners, dynamic elements not handled) and the solution (one listener on parent). matches() for target identification and closest() for finding the parent container are essential methods.

What is event delegation? | Hiprup