-
Notifications
You must be signed in to change notification settings - Fork 2
/
element_tagName.html
63 lines (55 loc) · 1.59 KB
/
element_tagName.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!doctype html>
<h1>Heading with a <span>span</span> element.</h1>
<p>A paragraph with <span>one</span>, <span>two</span>
spans.</p>
<script>
/////////////////
// My solution //
/////////////////
/* function byTagName(node, tagName) {
// Your code here.
let arrayOfNodes = [], count = 0;
// main task
if (node.nodeName === tagName.toUpperCase()) { arrayOfNodes[0] = node }
//base case
if (node.childNodes === 0) { return arrayOfNodes; }
// recursive case
for (var i = 0, n; i < node.childNodes.length; i++) {
if ((n = byTagName(node.childNodes[i],tagName)).length > 0) {
arrayOfNodes.push(...n);
}
}
// return for recursive case
return arrayOfNodes;
}
*/
////////////////////
// Their solution //
////////////////////
function byTagName (node, tagName) {
const found = [];
tagName = tagName.toUpperCase();
// helper function
function explore (node) {
for (var i = 0; i < node.childNodes.length; i++) {
let child = node.childNodes[i];
// Recursive case, otherwise is a base case condition
if (child.nodeType === Node.ELEMENT_NODE){
if (child.nodeName === tagName) { found.push(child)}
explore(child);
}
}
}
explore(node);
return found;
}
console.log(byTagName(document.body, "body").length);
// → 1
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>