Facebook Pixel

What Is Event Delegation in JavaScript?

One listener on the parent handles all children. Here is how event delegation works.

What Is Event Delegation in JavaScript?

Event delegation uses event bubbling to handle events for multiple children with a single listener on the parent.

Without Delegation

document.querySelectorAll("li").forEach((li) => { li.addEventListener("click", () => console.log(li.textContent)); });

100 items = 100 listeners. New items need new listeners.

With Delegation

document.querySelector("ul").addEventListener("click", (e) => { if (e.target.tagName === "LI") console.log(e.target.textContent); });

1 listener. Works for existing and new items.

Advantages

  • Memory: one listener instead of many.
  • Dynamic: works for newly added children.
  • Simpler: less code, easier to maintain.

Use Cases

  • Lists with many items.
  • Dynamically added elements.
  • Tables with clickable rows.
  • Menus with many items.

The Takeaway

Event delegation: one listener on the parent, check e.target to determine which child was clicked. Advantages: memory-efficient, works for dynamic children, simpler code. Built on event bubbling.

Using event bubbling to handle events for multiple children with a single listener on the parent. When a child is clicked, the event bubbles to the parent, which checks e.target to determine which child was clicked.

Memory-efficient (one listener instead of many), works for dynamically added children (no need to add new listeners), and simpler code (one handler instead of many).

Add one listener on the parent: parent.addEventListener('click', e => { if (e.target.matches('li')) handle(e.target); }). Check e.target to determine which child was clicked.

Yes. Since the listener is on the parent (which already exists), new children's clicks bubble to the same parent listener. No need to add new listeners. This is a key advantage.

Check e.target: if (e.target.tagName === 'LI') or if (e.target.matches('.item')). e.target is the element that triggered the event (the actual clicked child).

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.