Lesson 30 of 80
A click on a button doesn't just fire on the button — it fires on every ancestor too, on the way up. Delegation is putting one listener on the ancestor instead of hundreds on the children.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
A delegated click listener sits on a `<ul>`. A new `<li>` is added to the list after the listener was attached. Does clicking the new `<li>` still trigger the handler?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
When you click an element, the event doesn't just fire there — it bubbles: it fires on the element, then its parent, then that parent, all the way up to document. Event delegation puts a single listener on a shared ancestor instead of one listener per child, and uses event.target to figure out which child was actually clicked.
// Without delegation: one listener per item, and new items need new listeners
document.querySelectorAll(".item").forEach((item) => {
item.addEventListener("click", handleClick);
});
// With delegation: one listener, works for items added later too
document.querySelector(".list").addEventListener("click", (event) => {
const item = event.target.closest(".item");
if (item) handleClick(event);
});
The delegated version automatically handles items added to the list after the listener was attached — there's nothing to re-wire, because the listener lives on the parent, and every future click still bubbles up to it.
A click lands on one specific <li>. It doesn't just fire there — it bubbles.
onClick on individual elements.addEventListener(type, fn, true) listens during capture instead of bubble — rarely needed, but explains why the option exists.event.stopPropagation() stops the bubble, which can silently break delegation elsewhere in the app if an inner handler calls it without realizing an outer delegated listener depended on the event reaching it."You have a list of 10,000 items — how do you handle clicks efficiently, including items added dynamically?" is a direct, practical question, and delegation is the textbook-correct answer for both the performance and the dynamic-content parts at once.