Skip to the solution
MediumFrontendAsked in 20246 min read

DOM event delegation target

3.4k views

The problem

Problem, as an interviewer would state it: "Implement delegate(container, selector, eventType, handler) — attach ONE real listener to container, and have it correctly fire handler only when the actual clicked element matches selector, INCLUDING elements added to the DOM later."

Examples:

Code
delegate(list, "li", "click", (event, target) => console.log(target.textContent));
// works for every <li>, even ones added to the list AFTER this call

Clarifying questions expected:

  • Should this work correctly for elements added to the DOM AFTER the delegate() call — the whole real reason to use delegation over binding individual listeners?
  • What if the real click target is a nested element INSIDE a matching one (e.g., an icon inside an <li>)?
  • Does the handler need access to the actual matched element, not just the raw event?

Code / implementation expected: Yes — real, direct proof against a real DOM: a click on an element added AFTER the listener attached still correctly fires the handler, and a click on a non-matching element does not.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: delegation correctly fires for an element that already existed AND one added after attaching, but not for a non-matching element

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 55 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Clear Nullish Values

Continue