Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9048cd5

Browse files
Create elements_by_tag_name_completejavascript.com.js
1 parent 53752cf commit 9048cd5

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /