Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/b202465fa681221ed265234795820e19 to your computer and use it in GitHub Desktop.
Save yitonghe00/b202465fa681221ed265234795820e19 to your computer and use it in GitHub Desktop.
<h1>Heading with a <span>span</span> element.</h1>
<p>A paragraph with <span>one</span>, <span>two</span>
spans.</p>
<script>
function byTagName(node, tagName) {
const arr = [];
Array.from(node.children).forEach((child) => {
if (child.nodeName.toLowerCase() === tagName) {
arr.push(child);
}
arr.push(...byTagName(child, tagName))
});
return arr;
}
console.log(byTagName(document.body, "h1").length);
// → 1
console.log(byTagName(document.body, "span").length);
// → 3
let para = document.querySelector("p");
console.log(byTagName(para, "span").length);
// → 2
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment