getElementsByClassNameLoading saved progress…

getElementsByClassName

Reimplement the browser's Element.getElementsByClassName from scratch. Given a root element and a string of one or more space-separated class names, walk its subtree and return every descendant element that carries every one of those classes — in document order. It's a common interview question because it makes you traverse a tree and reason about class membership: an element matches if it contains each requested class, not if its class string is an exact match.

Signature

function getElementsByClassName(root: Element, classNames: string): Element[];

Returns a plain array (not a live HTMLCollection). classNames may be a single class ('active') or several separated by whitespace ('btn primary'); an element matches only if it has all of them.

Examples

const root = document.createElement('div');
root.innerHTML = '<p class="card hit">a</p><div><span class="hit">b</span></div>';

getElementsByClassName(root, 'hit');
// → [<p class="card hit">a</p>, <span class="hit">b</span>]
// both match: the first has 'hit' alongside 'card', the second is nested
const root = document.createElement('div');
root.innerHTML = '<div class="a">x</div><div class="b a">y</div>';

getElementsByClassName(root, 'a b'); // → [<div class="b a">y</div>]
// only the second has BOTH 'a' and 'b'; order in the class attribute is irrelevant

Notes

  • All classes required. For a multi-class query like 'a b', an element must have both a and b. Having only one is not a match.
  • Extra classes are fine. An element with class="card hit big" matches a query of 'hit' — you are checking membership, not equality.
  • Order does not matter. class="b a" matches a query of 'a b'.
  • Descendants only. The root itself is never included, even if it has the classes.
  • Every depth. Matches can be nested arbitrarily deep — search the whole subtree, not just direct children.
  • Document order. Results come back in the order the elements appear (a pre-order traversal).
Loading editor…