Last active
May 12, 2022 04:26
-
-
Save yitonghe00/b202465fa681221ed265234795820e19 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<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