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.
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.
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.
1 to 10^4 elements; containerId and targetId exist.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).
I'm here to help with #708 Resolve a Delegated Click. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.