Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created April 30, 2024 03:12
Show Gist options
  • Save amitasaurus/c8be4172bd00719b24e1f5f3056f4de6 to your computer and use it in GitHub Desktop.
Save amitasaurus/c8be4172bd00719b24e1f5f3056f4de6 to your computer and use it in GitHub Desktop.
`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.
export default function getElementsByTagName(
el: Element,
tagName: string,
): Array<Element> {
const elements: Array<Element> = [];
function traverseNode(el: Node) {
const nodes = el.childNodes;
nodes.forEach((node) => {
if (node.nodeName === tagName.toUpperCase()) {
elements.push(node as Element);
}
if (node.hasChildNodes()) {
traverseNode(node);
}
});
}
traverseNode(el);
return elements;
}
@amitasaurus
Copy link
Author

amitasaurus commented Apr 30, 2024

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment