← All Exercises
Event Delegation Selector Matcher
intermediatejavascript
Background
Delegated event listeners attach one handler to a container instead of many handlers to individual children, but the handler still has to decide which ancestor should receive the event.
Problem
Given an array of ancestor descriptors from the event target upward and a compound selector, return the index of the nearest element that matches, or -1. Support tag names, #id, .class, and [attr] or [attr='value'] tokens combined in one selector.
Input
A JSON object with path (each entry has tag, optional id, classes, attrs) and a selector string.
Output
The zero-based index of the closest matching element in path, or -1 when nothing matches.
Sample tests
Sample 1
Input: {"path":[{"tag":"button","classes":["btn","primary"],"attrs":{"data-action":"save"}},{"tag":"div","id":"toolbar","classes":[],"attrs":{}},{"tag":"body","classes":[],"attrs":{}}],"selector":"button[data-action='save']"}Expected: 0
Sample 2
Input: {"path":[{"tag":"span","classes":[],"attrs":{}},{"tag":"div","id":"toolbar","classes":["toolbar"],"attrs":{}},{"tag":"body","classes":[],"attrs":{}}],"selector":".toolbar"}Expected: 1
Sample 3
Input: {"path":[{"tag":"a","classes":["link"],"attrs":{"href":"/"}},{"tag":"li","classes":[],"attrs":{}},{"tag":"ul","id":"menu","classes":["menu"],"attrs":{}}],"selector":"a.link[href='/']"}Expected: 0
Sample 4
Input: {"path":[{"tag":"a","classes":["link"],"attrs":{"href":"/"}}],"selector":"#missing"}Expected: -1
Your solution
Learning objective
Learn selector token parsing, compound matching rules, and closest-ancestor traversal used by delegated event handlers.