mediumcodingjavascript~10 min
Find the Delegated Event Target
Objective: Model event delegation: walk up from the target but never past the delegating root.
Event delegation needs the nearest ancestor of `event.target` that matches a selector. Implement `closestMatch(target, root, matches)` on plain node objects with a `parentNode` link.
- Start at `target` itself and walk up through `parentNode`.
- Return the first node for which `matches(node)` is true.
- Stop at `root` (inclusive) and return null if nothing matched.
- Return null if root is never reached or target is null.
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- Why does delegation work for elements added after the listener was attached?
- Which events do not bubble, and how do you delegate those?
- What does the real Element.closest do differently?