jQuery jAM, Season 6

Exercise 13.02

Elements by Tag Name

	 

Heading with a span element.

A paragraph with one, two spans.

function byTagName(node, tagName){ var found = []; tagName = tagName.toUpperCase(); function explore(node){ for(var i = 0; i < node.childNodes.length; i++) { var child = node.childNodes[i]; if(child.nodeType == document.ELEMENT_NODE) { if(child.nodeName == tagName) found.push(child); explore(child); } } } explore(node); return found; } console.log(byTagName(document.body, "h1").length); // -> 1 console.log(byTagName(document.body, "span").length); //->3 var para = document.querySelector("p"); console.log(byTagName(para, "span").length); //->2

To open the JavaScript console, press F12 or on MAC press COMMAND-OPTION-I.