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

PropertyReturnsExample
nodeNameName of the node"DIV", "#text", "#comment"
nodeTypeNumeric type1 (element), 3 (text), 8 (comment)
nodeValueValue of text/comment nodes"Hello" or null for elements
hasChildNodes()Booleantrue 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
PropertyReturnsIncludes Text/Comment?
childNodesNodeListYes — all node types
childrenHTMLCollectionNo — element nodes only

Key Takeaways

  • Everything in the DOM is a node — elements, text, comments, whitespace
  • nodeType identifies the type: 1 = element, 3 = text, 8 = comment
  • childNodes returns all nodes; children returns only element nodes
  • Whitespace in HTML creates text nodes — be aware of this when traversing