JavaScript › DOM & Events

What is event delegation and why is it a performance best practice?

Intermediate

Answer

Event delegation attaches a single listener to a common ancestor and uses event.target to determine which child triggered it, instead of attaching a separate listener to every child — this uses far less memory and automatically works for dynamically added children.
document.getElementById('list').addEventListener('click', (e) => {
  if (e.target.matches('li')) {
    console.log('Clicked item:', e.target.textContent);
  }
});
Real-world example Handling clicks on rows of a dynamically loaded, potentially thousands-of-items-long table.

Common follow-ups: What DOM property tells you which element actually triggered the event versus which listener caught it?