Created
April 30, 2024 03:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Author
amitasaurus
commented
Apr 30, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment