getElementsByTagNameLoading saved progress…

getElementsByTagName

Reimplement the browser's Element.getElementsByTagName from scratch. Given a root element and a tagName, walk its subtree and return every descendant element whose tag matches — in document order. It's a classic interview question because it forces you to traverse a tree, handle case-insensitive tag matching, and remember the rules the real API follows (the root is never part of the result; '*' matches everything).

Signature

function getElementsByTagName(root: Element, tagName: string): Element[];

Returns a plain array (not a live HTMLCollection). tagName matching is case-insensitive; '*' matches every element.

Examples

const root = document.createElement('div');
root.innerHTML = '<p>a</p><div><p>b</p></div>';

getElementsByTagName(root, 'p');
// → [<p>a</p>, <p>b</p>]   (both, including the nested one, in order)
getElementsByTagName(root, '*');     // every descendant element
getElementsByTagName(root, 'video'); // []  (no match)

Notes

  • Descendants only. The root itself is never included, even if its tag matches the query.
  • Every depth. Matches can be nested arbitrarily deep — you must search the whole subtree, not just direct children.
  • Document order. Results come back in the order they appear in the document (a pre-order traversal).
  • Case-insensitive. getElementsByTagName(root, 'div') and 'DIV' behave identically. '*' is a wildcard that matches all elements.
  • Elements only. Skip text nodes and comments — return only element nodes.
Loading editor…