getByClassName(root, name) is a depth-first walk of root's descendants, collecting those whose classList contains the name, in document order. getByClassnameHierarchy(root, 'a>b>c') returns elements with class c whose parent has b and whose grandparent has a. The simple version goes level by level: find every a, then their children with b, then theirs with c. A single walk is better. Pass each node the set of chain positions that end at its parent: a node extends position k - 1 to k if it has names[k]. That gives document order, handles repeated names like a>a>b, and runs in O(nodes × path length). Adding a descendant combinator (a b) means also passing down what ended at any ancestor.
Implement getByClassName() and getByClassnameHierarchy()
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
getByClassName recurses into children, checking each one. Root is excluded, like element.getElementsByClassName. The hierarchy starts from every node with the first class (root included, since a chain can start there), then keeps only the children that match the next name, once per name. It's correct, but the results come out grouped by where each chain started, not in document order.
// All descendants of root that have the class (root itself excluded, like the DOM method).function getByClassName(root, className) {const out = [];for (const child of root.children) {if (child.classList.contains(className)) out.push(child);out.push(...getByClassName(child, className));}return out;}// 'a>b>c': elements with class c whose parent has b and grandparent has a. The chain may start// at root. Level by level: everything matching a, then their children matching b, and so on.function getByClassnameHierarchy(root, path) {const [first, ...rest] = path.split('>').map((s) => s.trim());let level = [...(root.classList.contains(first) ? [root] : []), ...getByClassName(root, first)];for (const name of rest) {level = level.flatMap((node) => [...node.children].filter((child) => child.classList.contains(name)));}return level.filter((node) => node !== root);}
passes 4 checks run on every build, against the native method where there is one
- getByClassName finds descendants in document order
- hierarchy follows direct parents only
- a single name is getByClassName
- no match gives an empty list
Walk once with an explicit stack, so deep trees can't overflow. Each node computes which chain positions end exactly at it: position k if it has names[k] and its parent completed k - 1 (or k = 0). Use a set rather than a single counter, because with a>a>b one node can end both a and a>a. The first check shows a case where the level-by-level version returns results out of order. The third compares against a brute-force definition on 200 random trees.
function getByClassName(root, className) {const out = [];const stack = [...root.children].reverse();while (stack.length) {const node = stack.pop();if (node.classList.contains(className)) out.push(node);for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i]);}return out;}// One walk in document order. Each node carries the set of k for which the chain names[0..k]// ends exactly at it: k matches if the node has names[k] and its parent completed k - 1.// A set, not one counter, because names can repeat ('a>a>b').function getByClassnameHierarchy(root, path) {const names = path.split('>').map((s) => s.trim());if (names.some((n) => !n)) throw new SyntaxError(`invalid path: ${path}`);const last = names.length - 1;const endsAt = (node, parentEnds) =>new Set(names.flatMap((name, k) => (node.classList.contains(name) && (k === 0 || parentEnds.has(k - 1)) ? [k] : [])));const out = [];const stack = [...root.children].reverse().map((node) => [node, endsAt(root, new Set())]);while (stack.length) {const [node, parentEnds] = stack.pop();const ends = endsAt(node, parentEnds);if (ends.has(last)) out.push(node);for (let i = node.children.length - 1; i >= 0; i--) stack.push([node.children[i], ends]);}return out;}
passes 5 checks run on every build, against the native method where there is one
- results in document order (the level-by-level version isn't)
- repeated names: a>a>b
- matches the definition on 200 random trees
- a 50,000-deep tree doesn't overflow
- empty parts are rejected
Support CSS's two combinators: > (parent) and a space (any ancestor). Each node passes down two sets: what ends exactly at it, and what ends at it or anywhere above. For each position, > checks the first set and a space checks the second. It's still one walk with no backtracking, compared against the definition on random trees with mixed combinators. In a real browser this is root.querySelectorAll('.a > .b .c'), which also returns tree order.
// Both combinators, like CSS: 'a > b' means parent, 'a b' means any ancestor.function parse(path) {const tokens = path.trim().split(/(\s*>\s*|\s+)/);const names = tokens.filter((_, i) => i % 2 === 0);const combinators = [null, ...tokens.filter((_, i) => i % 2 === 1).map((t) => (t.includes('>') ? '>' : ' '))];if (names.some((n) => !/^[\w-]+$/.test(n))) throw new SyntaxError(`invalid path: ${path}`);return { names, combinators };}// Each node passes down two sets: what ends exactly at it (for '>') and what ends at it or any// ancestor (for ' '). One walk, no recursion, results in document order.function getByClassnameHierarchy(root, path) {const { names, combinators } = parse(path);const last = names.length - 1;const step = (node, parent, above) => {const ends = new Set();names.forEach((name, k) => {if (!node.classList.contains(name)) return;if (k === 0 || (combinators[k] === '>' ? parent : above).has(k - 1)) ends.add(k);});return { ends, above: new Set([...above, ...ends]) };};const top = step(root, new Set(), new Set());const out = [];const stack = [...root.children].reverse().map((node) => [node, top.ends, top.above]);while (stack.length) {const [node, parent, above] = stack.pop();const here = step(node, parent, above);if (here.ends.has(last)) out.push(node);for (let i = node.children.length - 1; i >= 0; i--) stack.push([node.children[i], here.ends, here.above]);}return out;}
passes 3 checks run on every build, against the native method where there is one
- '>' is parent, a space is any ancestor
- matches the definition with mixed combinators on 200 random trees
- parse splits names and combinators
Browsers match selectors right to left
Engines check a selector like .a > .b .c starting from .c and walk up through ancestors. Our walk goes top-down instead, carrying state, which suits a one-off query over a tree.
querySelectorAll returns tree order
The DOM spec defines results in tree order, a preorder depth-first walk, which is the order our single-walk version produces.
Scraping and test selectors
Testing libraries and scrapers query trees that aren't live DOMs (server HTML, virtual DOM snapshots) with exactly this kind of matcher.
Matching
a>b>cas "has a, b and c somewhere above" instead of direct parents.A single counter for the matched position, which breaks on repeated names like
a>a>b.Results out of document order from the level-by-level approach.
Comparing
className === nameinstead ofclassList.contains, which misses elements with several classes.Recursion on very deep trees.
What's the complexity?
Each node is visited once and checks every path position: O(n · k) time for n nodes and k names, and O(depth · k) extra space for the stack and sets (O(n · k) in the worst case for the stack's pending children).
How would you support .a.b (both classes on one element)?
Make each path step a list of classes and check that the node contains all of them.
Live vs static results?
getElementsByClassName returns a live HTMLCollection that updates as the DOM changes; querySelectorAll returns a static NodeList. Our functions return static arrays.