← All tutorials

GoCareerGo Tutorials

JavaScript Tutorial

Variables to closures, promises, the DOM and OOP — a complete JS reference.

Event Delegation

Attach one listener to a parent element instead of many listeners on each child — using event bubbling.

document.querySelector('#list').addEventListener('click', (e) => {
  if (e.target.matches('li')) {
    console.log('Clicked item:', e.target.textContent);
  }
});
// Works even for <li> elements added to the list LATER
  • Fewer event listeners → better memory usage
  • Automatically works for dynamically added child elements
  • Relies on e.target to identify which child was actually clicked
Tip

Explain WHY it works: events bubble up from the target to ancestors, so the parent's listener still fires.