JS DOM: Whitespace Nodes
What is Whitespace Node
Whitespace characters in HTML source code between elements are considered a node too. (whitespace includes space, newline, tab)
Example of Whitespace Node
For example, if you have:
<ul id="V8j74"> <li>A</li> <li>B</li> </ul>
The newline characters between tags, are whitespace nodes.
If you count the number of the ul's children nodes, you get 5.
/* demonstrate whitespace nodes */ // create a div const xdiv = document.createElement("div"); // create inner html xdiv.innerHTML = ` <ul id="V8j74"> <li>A</li> <li>B</li> </ul> `; // add to the page document.body.prepend(xdiv); // get the list let xlist = document.getElementById("V8j74"); // got 5 children nodes console.log(xlist.childNodes.length === 5); // get the first child const x1child = xlist.firstChild; // value is newline console.log(x1child.nodeValue === "\n"); // true
How to Skip Whitespace Nodes
You can check the Node Type and decide if you need to skip it.
Or use the following methods that ignore whitespace nodes.
childrennextElementSiblingpreviousElementSiblingfirstElementChildlastElementChildparentElement
Reference