Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jasontwuk/9749802fb32c83da0bf322208f2894e3 to your computer and use it in GitHub Desktop.
Save jasontwuk/9749802fb32c83da0bf322208f2894e3 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Ch14-exercise-Element By Tag Name</title>
</head>
<body>
<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) {
let array = [];
function searchForNode(node){
for(let i = 0; i < node.childNodes.length; i++){
let child = node.childNodes[i];
if(child.nodeType == document.ELEMENT_NODE){
if(child.nodeName.toLowerCase() == tagName){
array.push(child);
}
}
searchForNode(child);
}
}
searchForNode(node);
return array;
}
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>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment