Walk the element tree depth first from the root's children, leaving the root itself out, and collect every element whose classList contains the class. Depth-first pre-order (a parent before its descendants, siblings left to right) gives document order, which the real method guarantees. Then match the real API's details: the argument may hold several classes separated by spaces and an element must have all of them, in any order; the comparison is case-sensitive in standards mode; and an empty argument matches nothing. Follow-ups to expect: do it without recursion (an explicit stack, pushing children in reverse), say that the real method returns a live HTMLCollection while yours returns a snapshot array, and extend the same walk to tag names or simple selectors.
Write a getElementsByClassName function.
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.
Visit each child, test it, then recurse into it: that's depth-first pre-order, which is document order. Start from the root's children because the real methods return descendants only. classList.contains is case-sensitive (class matching ignores ASCII case only in quirks-mode documents); tag names are upper-cased because HTML elements report tagName in upper case. The checks run on a small stand-in for elements that has only the properties used here: children, tagName, id and classList.contains.
// Every descendant (not the root itself), in document order, that has the class.function getElementsByClassName(root, className) {const out = [];const visit = (node) => {for (const child of node.children) {if (child.classList.contains(className)) out.push(child);visit(child); // depth first: a parent comes before its descendants}};visit(root);return out;}function getElementsByTagName(root, tagName) {const want = tagName.toUpperCase(); // HTML tag names match without regard to caseconst out = [];const visit = (node) => {for (const child of node.children) {if (want === '*' || child.tagName === want) out.push(child);visit(child);}};visit(root);return out;}
passes 4 checks run on every build, against the native method where there is one
- finds descendants with the class, in document order
- the root itself is not included
- class names are case-sensitive
- tag names match without regard to case; * matches all
getElementsByClassName('a b') means elements with both classes, in any order; split on whitespace and require every one. A generator over an explicit stack yields the same document order (push children in reverse) without recursion, so a pathological 20,000-deep tree doesn't blow the call stack, and both functions share one traversal.
// One traversal, many filters. An explicit stack instead of recursion: no stack overflow on very// deep trees, and children are pushed in reverse so they come out in document order.function* descendants(root) {const stack = [...root.children].reverse();while (stack.length) {const node = stack.pop();yield node;for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i]);}}// "a b" means elements that have both classes, in any order, like the real API.function getElementsByClassName(root, classNames) {const wanted = classNames.split(/\s+/).filter(Boolean);if (wanted.length === 0) return [];const out = [];for (const node of descendants(root)) if (wanted.every((c) => node.classList.contains(c))) out.push(node);return out;}function getElementsByTagName(root, tagName) {const want = tagName.toUpperCase();const out = [];for (const node of descendants(root)) if (want === '*' || node.tagName === want) out.push(node);return out;}
passes 3 checks run on every build, against the native method where there is one
- several classes must all be present, in any order
- same order as the recursive version
- a 20,000-deep tree doesn't overflow the stack
Parse each compound selector (p.card, #app, div.card.shadow) into a predicate, then handle the descendant combinator by matching right to left: test the node against the last part, then walk up its ancestors looking for the earlier parts in order. Browsers match this way because most elements fail the rightmost part immediately. Anything this parser doesn't support throws a SyntaxError, as the real method does for invalid selectors.
function* descendants(root) {const stack = [...root.children].reverse();while (stack.length) {const node = stack.pop();yield node;for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i]);}}// A compound selector like "p.card", "#app" or "div.card.shadow".function parseCompound(text) {const m = /^([a-zA-Z][\w-]*|\*)?((?:[.#][\w-]+)*)$/.exec(text);if (!m) throw new SyntaxError(`unsupported selector: ${text}`);const tag = m[1] && m[1] !== '*' ? m[1].toUpperCase() : null;const classes = [...m[2].matchAll(/\.([\w-]+)/g)].map((x) => x[1]);const ids = [...m[2].matchAll(/#([\w-]+)/g)].map((x) => x[1]);return (node) => (!tag || node.tagName === tag) && classes.every((c) => node.classList.contains(c)) && ids.every((id) => node.id === id);}// querySelectorAll for compound selectors joined by spaces (the descendant combinator).// Matched right to left, as browsers do: test the node, then look for ancestors that match the rest.function querySelectorAll(root, selector) {const parts = selector.trim().split(/\s+/).map(parseCompound);const out = [];const walk = (node, ancestors) => {for (const child of node.children) {if (parts.at(-1)(child)) {let need = parts.length - 2;for (let a = ancestors.length - 1; a >= 0 && need >= 0; a--) if (parts[need](ancestors[a])) need--;if (need < 0) out.push(child);}walk(child, [...ancestors, child]);}};walk(root, []);return out;}
passes 3 checks run on every build, against the native method where there is one
- compound selectors: tag, classes and id together
- descendant combinator, matched against ancestors
- unsupported selectors throw a SyntaxError, like the real API
Live collections surprise people
getElementsByClassName returns a live HTMLCollection: removing the class from items while looping over it shrinks the collection under you and skips every other item. querySelectorAll returns a static NodeList, which is why modern code prefers it.
Why browsers match selectors right to left
For .sidebar a, checking every a and then walking up to find .sidebar rejects most elements at the first test. That's also why a long descendant chain ending in a common tag (div *) is the slow kind of selector.
TreeWalker for real traversal
In a browser, document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT) walks elements in document order without recursion; it's the built-in version of the intermediate stage's generator.
Including the root element in the results: the real methods return descendants only.
Breadth-first traversal: results come out in the wrong order.
Testing
className === name, which fails when an element has several classes.Treating
'a b'as one class name instead of 'has both a and b'.Looping over a live
HTMLCollectionwhile changing the classes it filters on.Recursing over
childNodesand testing text nodes, which have noclassList.
What's the difference between children and childNodes?
children holds only element nodes; childNodes also holds text and comment nodes. Element searches walk children.
How would you make the result live?
Return an object whose length and index access recompute on read, or cache the result and invalidate it with a MutationObserver on the root ({ subtree: true, childList: true, attributes: true }). Browsers keep such caches internally.
What's the time complexity?
O(n) elements visited for the class and tag searches. The descendant-combinator matcher is O(n·d) in the worst case, where d is the depth, because each candidate may walk its ancestors.
- developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
- developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
- dom.spec.whatwg.org/#concept-getelementsbyclassname
- dom.spec.whatwg.org/#concept-getelementsbytagname
- developer.mozilla.org/en-US/docs/Web/API/Element/tagName
- developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll