Skip to the code
cf.
+25 XP

#708 Resolve a Delegated Click

medium

A shopping cart uses event delegation: one click listener on the container element handles clicks for every row. The listener must find which element with a certain class was clicked, even when the click lands on an icon inside it, like event.target.closest(".btn") combined with a check that the match is inside the container.

Write delegatedTarget(root, containerId, targetId, className). Starting at the element targetId and moving up through its ancestors, return the id of the first element whose classes include className. Stop after checking the container itself: never look above it. If targetId is neither the container nor inside it, or nothing matches, return null.

Elements have tag, id, optional classes, and optional children.

Example 1

Input: root = {"tag":"div","id":"app","classes":["app"],"children":[{"tag":"ul","id":"cart","classes":["list"],"children":[{"tag":"li","id":"row1","classes":["item"],"children":[{"tag":"span","id":"name1","classes":["label"]},{"tag":"button","id":"del1","classes":["btn","danger"],"children":[{"tag":"svg","id":"icon1","classes":["icon"]}]}]},{"tag":"li","id":"row2","classes":["item","active"],"children":[{"tag":…, containerId = "cart", targetId = "icon1", className = "btn"
Output: "del1"

The click landed on the icon; its parent button#del1 has the btn class.

Example 2

Input: root = {"tag":"div","id":"app","classes":["app"],"children":[{"tag":"ul","id":"cart","classes":["list"],"children":[{"tag":"li","id":"row1","classes":["item"],"children":[{"tag":"span","id":"name1","classes":["label"]},{"tag":"button","id":"del1","classes":["btn","danger"],"children":[{"tag":"svg","id":"icon1","classes":["icon"]}]}]},{"tag":"li","id":"row2","classes":["item","active"],"children":[{"tag":…, containerId = "cart", targetId = "pay", className = "btn"
Output: null

button#pay is in the footer, outside the cart container.

Constraints

  • The tree has 1 to 10^4 elements; containerId and targetId exist.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).