code
1 2 3 4 |
<header> <h1 class="heading" id="mainHeading"><p>JavaScript Fundamentals</p></h1> <h2 class="heading subHeading">Part of the Front End Development learning path by Tuts+</h2> </header> |
js
1 2 3 4 5 |
//get first (0th index) header var heading = document.getElementsByTagName('header')[0]; console.log(heading); console.log(heading.childNodes); console.log(heading.childNodes.length); // 5 |
You’d get the element by tag name which is header. Then you the childNodes list, which can contain any node types. This includes:
NodeType Description
1 Element Represents an element Element, Text, Comment,
2 Attr Represents an attribute Text, EntityReference
3 Text Represents textual content in an element or attribute None
…..
….
….
Hence that’s why we see type Element and Text in our results. Finally, we see the total number of nodes representations which is 5.
result:
header
[text, h1#mainHeading.heading, text, h2.heading.subHeading, text]
5
Now let’s traverse this list. We go through each node in the childNode property and list their attributes. We want to see what kind of node types they are. In our case, we see that its all node types 1 and 3.
We also say that if the node type is 1, we want it to print out its tag name
1 2 3 4 5 6 7 8 9 10 11 12 |
console.log('-----------------------'); var x, length; for (x = 0, length = heading.childNodes.length; x < length; x += 1) { console.log('nodeType: ' + heading.childNodes[x].nodeType); if (heading.childNodes[x].nodeType === 1) { console.log('Its of nodeType 1! ....I am a ' + heading.childNodes[x].tagName + ' tag'); // I am a P... } } console.log('-----------------------'); |
result:
———————–
elements.js:89 nodeType: 3
elements.js:89 nodeType: 1
elements.js:92 Its of nodeType 1! ….I am a H1 tag
elements.js:89 nodeType: 3
elements.js:89 nodeType: 1
elements.js:92 Its of nodeType 1! ….I am a H2 tag
elements.js:89 nodeType: 3
elements.js:97
———————–
Most of the time, we just want to see the children element nodes, thus you can use the property children. Hence some of the more common properties can you can use are childNodes, children, and also firstChild/lastChild and nextSibling/previousSibling.
1 2 3 4 5 6 7 8 9 10 11 |
console.log('length of heading.children (child elements only): ' + heading.children.length); // 2 console.log(heading.childNodes[0].nodeName); // #text console.log(heading.children[0].nodeName); // P console.log(heading.firstChild.nodeName); // #text console.log(subHeading.parentNode.nodeName); // HEADER console.log(heading.firstChild.nextSibling.nodeName); // P console.log(heading.lastChild.previousSibling.nodeName); // H |