|  | 
|  | 1 | +<h1>Heading with a <span>span</span> element.</h1> | 
|  | 2 | +<p>A paragraph with <span>one</span>,<span>two</span> | 
|  | 3 | + spans.</p> | 
|  | 4 | + | 
|  | 5 | +<script> | 
|  | 6 | + function byTagName(node, tagName) { | 
|  | 7 | + function check(node, tagName) { | 
|  | 8 | + if (node.nodeType !== document.ELEMENT_NODE) return; | 
|  | 9 | + for (var i = 0; i < node.childNodes.length; i++) { | 
|  | 10 | + var nodeChild = node.childNodes[i]; | 
|  | 11 | + if (nodeChild.nodeType == document.ELEMENT_NODE) { | 
|  | 12 | + if (nodeChild.tagName.toLowerCase() === tagName.toLowerCase()) | 
|  | 13 | + elements.push(nodeChild); | 
|  | 14 | + check(nodeChild, tagName); | 
|  | 15 | + }  | 
|  | 16 | + }  | 
|  | 17 | + } | 
|  | 18 | + | 
|  | 19 | + var elements = []; | 
|  | 20 | + check(node, tagName); | 
|  | 21 | + return elements; | 
|  | 22 | + } | 
|  | 23 | + | 
|  | 24 | + console.log(byTagName(document.body, "h1").length); | 
|  | 25 | + // => 1 | 
|  | 26 | + console.log(byTagName(document.body, "span").length); | 
|  | 27 | + // => 3 | 
|  | 28 | + var para = document.querySelector("p"); | 
|  | 29 | + console.log(byTagName(para, "span").length); | 
|  | 30 | + // => 2 | 
|  | 31 | +</script> | 
|  | 32 | + | 
|  | 33 | +/* | 
|  | 34 | +<h1>Heading with a <span>span</span> element.</h1> | 
|  | 35 | +<p>A paragraph with <span>one</span>, <span>two</span> | 
|  | 36 | + spans.</p> | 
|  | 37 | + | 
|  | 38 | +<script> | 
|  | 39 | + function byTagName(node, tagName) { | 
|  | 40 | + var elements = []; | 
|  | 41 | + var all = document.getElementsByTagName(tagName); | 
|  | 42 | + | 
|  | 43 | + Array.prototype.forEach.call(all, function(element){ | 
|  | 44 | + 	if(node.contains(element)) { | 
|  | 45 | + elements.push(element); | 
|  | 46 | + } | 
|  | 47 | + }); | 
|  | 48 | + | 
|  | 49 | + return elements; | 
|  | 50 | + } | 
|  | 51 | + | 
|  | 52 | + console.log(byTagName(document.body, "h1").length); | 
|  | 53 | + // => 1 | 
|  | 54 | + console.log(byTagName(document.body, "span").length); | 
|  | 55 | + // => 3 | 
|  | 56 | + var para = document.querySelector("p"); | 
|  | 57 | + console.log(byTagName(para, "span").length); | 
|  | 58 | + // => 2 | 
|  | 59 | +</script> | 
|  | 60 | +*/ | 
0 commit comments