logo

Event Delegation

How event delegation works in the DOM and why it's efficient for dynamic content.

Short explanation

Event delegation attaches a single listener to a parent element to handle events from child elements via event bubbling, reducing listeners and improving performance for dynamic lists.

Example

document.querySelector('#list').addEventListener('click', function (e) {
  const item = e.target.closest('.item');
  if (item) console.log('clicked', item.dataset.id);
});

How JS handles it internally

Events bubble from the target up through ancestors. Delegation leverages this to handle many potential targets via one listener, avoiding attaching many listeners to individual elements.

FAQ

Q: Does delegation work for all events?

A: Most bubbleable events support delegation; some events (like focus) do not bubble and need other strategies.