Episode 6 of 18
Nodes
Understand DOM nodes — element nodes, text nodes, comment nodes — and how every piece of the page is a node in the tree.
Nodes
Everything in the DOM is a node. Elements, text, comments, even whitespace — they are all nodes. Understanding node types is essential for traversing and manipulating the DOM accurately.
Node Types
<div id="wrapper">
<!-- A comment -->
<p>Hello World</p>
</div>
Nodes inside #wrapper:
1. Text node (whitespace/newline)
2. Comment node ("A comment")
3. Text node (whitespace)
4. Element node (<p>)
└── Text node ("Hello World")
5. Text node (whitespace)
Node Properties
| Property | Returns | Example |
|---|---|---|
nodeName | Name of the node | "DIV", "#text", "#comment" |
nodeType | Numeric type | 1 (element), 3 (text), 8 (comment) |
nodeValue | Value of text/comment nodes | "Hello" or null for elements |
hasChildNodes() | Boolean | true if the node has children |
Exploring Nodes
var wrapper = document.getElementById('wrapper');
console.log(wrapper.nodeName); // "DIV"
console.log(wrapper.nodeType); // 1 (element)
console.log(wrapper.hasChildNodes()); // true
var children = wrapper.childNodes;
console.log(children); // NodeList(5)
children.forEach(function(node) {
console.log(node.nodeName, node.nodeType);
});
// #text 3
// #comment 8
// #text 3
// P 1
// #text 3
Notice that whitespace between elements creates text nodes. This is why childNodes often contains more nodes than you expect.
childNodes vs children
var wrapper = document.getElementById('wrapper');
console.log(wrapper.childNodes); // All nodes (text, comment, element)
console.log(wrapper.children); // Only element nodes
| Property | Returns | Includes Text/Comment? |
|---|---|---|
childNodes | NodeList | Yes — all node types |
children | HTMLCollection | No — element nodes only |
Key Takeaways
- Everything in the DOM is a node — elements, text, comments, whitespace
nodeTypeidentifies the type: 1 = element, 3 = text, 8 = commentchildNodesreturns all nodes;childrenreturns only element nodes- Whitespace in HTML creates text nodes — be aware of this when traversing