JS DOM: Whitespace Nodes

By Xah Lee. Date: . Last updated: .

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.

[see JS DOM: Get Parent, Child, Sibling]

Reference

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