getElementsByTagName() is a method which exists on the Document and Element objects and returns an HTMLCollection of descendant elements within the Document/Element given a tag name.

Let's implement our own Element.getElementsByTagName() that is similar but slightly different:

Do not use document.querySelectorAll() which will otherwise make the problem trivial.

Examples

const doc = new DOMParser().parseFromString(
  `<div id="foo">
    <span>Span</span>
    <p>Paragraph</p>
    <div id="bar">Div</div>
  </div>`,
  'text/html',
);

getElementsByTagName(doc.body, 'div');
// [div#foo, div#bar] <-- This is an array of elements.

Resources

Editorial

Step-by-Step Explanation — DFS DOM Traversal