Skip to main content
Practice Problems

Event delegation

What is Event Delegation?

Event delegation is a technique in JavaScript where an event handler is attached to a parent element, rather than to each child element separately.

This technique works thanks to the event bubbling mechanism โ€” an event first occurs on the target element, then bubbles up through the DOM tree.


Simple Example

Suppose you have a list:

html
<ul id="menu"> <li>Home</li> <li>About</li> <li>Contact</li> </ul>

Instead of attaching a click handler to each <li>, you can attach one handler to <ul>:

javascript
const menu = document.getElementById("menu"); menu.addEventListener("click", (event) => { const target = event.target; if (target.tagName === "LI") { console.log("You clicked on:", target.textContent); } });

How Does it Work?

  • User clicks on <li>.
  • Event bubbles from <li> to <ul>.
  • Handler on <ul> catches this event.
  • We check event.target to understand which exact element was clicked.

Advantages of Event Delegation

  • Fewer handlers โ†’ less memory consumption.
  • Works with dynamic elements that weren't initially in DOM.
  • Simplifies event management when DOM changes.

Disadvantages and Cautions

  • Always need to check event.target to ensure event occurred on the right element.
  • May have unwanted behavior if DOM structure changes dynamically.
  • Doesn't work if event doesn't bubble (e.g., blur, focus, scroll โ€” for them you need to use capture).

Tip:

Delegation is especially useful when you have many similar elements and want to attach a handler once โ€” efficient and clean.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems