DOM: Whitespace Nodes

By Xah Lee. Date: . Last updated: .

Whitespace characters in HTML source code between elements are considered a node too. (whitespace includes space, newline, tab) [see What is Node, Node Type, Element]

For example, if you have:

<ul id="x1">
<li>A</li>
<li>B</li>
</ul>

The newline character between tags, are whitespace nodes.

If you count the number of the ul's children nodes, you get 5.

document.getElementById("x1").childNodes.length;

Here is another example, you can try in browser console:

// get the next node after the first paragraph
let xx = document.getElementsByTagName("p")[0].nextSibling;

console.log(xx.nodeType);
// 3 means text node (whitespace node)

console.log(xx.nodeValue);
// if whitespace node, then result is space or newline or tab, etc.

[see JavaScript/DOM: What is Node, Node Type, Element]

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.

[see JS: Get Element's Parent/Child/Sibling, Navigate DOM Tree]

Reference

whitespace nodes 2019-05-26 d5bqv
whitespace nodes [https://developers.whatwg.org/introduction.html#a-quick-introduction-to-html]

JavaScript/DOM: Node Name, Node Type, Node Value

BUY Ξ£JS JavaScript in Depth