How to delegate events in JavaScript

· Category: JavaScript

Short answer

Event delegation attaches a single event listener to a parent element and uses event.target to handle events from its descendants, improving memory usage and supporting dynamic content.

Steps

  1. Attach one listener to the parent: javascript document.querySelector("#list").addEventListener("click", (e) => { if (e.target.matches("li.item")) { console.log("Item clicked:", e.target.dataset.id); } });
  2. Use closest() when the target might be a child of the intended element: javascript const item = e.target.closest("li.item"); if (item) { /* handle */ }
  3. Avoid handling clicks on the parent itself when not needed: javascript if (e.target === e.currentTarget) return;

Tips

  • Delegation works because most events bubble up from the target.
  • It automatically handles elements added after the listener is attached.

Common issues

  • Events that do not bubble (like focus or blur without capture) cannot be delegated easily.
  • Accidentally handling events from nested unrelated elements if the selector check is too broad.