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)

For example, if you have:

<ul id="x1">

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

    document .getElementById("x1").childNodes.length
); // prints 5

because the newline characters in between tags are also considered nodes.

Here's another example, you can try in browser console:

// example of testing whitespace node

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

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

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

[see DOM: Node Type, Node Name, Node Value]

How to Skip Whitespace Nodes

Use a property that skip the whitespace nodes.

no whitespace nodecontains whitespace node

Those “no whitespace” versions are newer, but is supported by all browsers today.

[see DOM: Navigate DOM Tree]


In XML, all whitespace has to be passed through to the application. This means that if you have whitespace, such as carriage returns, between tags in your source file, these have to be passed through, even if they're just there for pretty-printing. The DOM implementation has to put this whitespace somewhere, and the only possibility is a text node. Thus you will get text nodes which look empty, but in fact have a carriage return or other whitespace in them.

Note that some DOM implementations, which do not consider whitespace in element content to be meaningful for the XML languages they support, discard these whitespace nodes before exposing the DOM to their users.


There are many more Text nodes in the DOM tree than one would initially expect, because the source contains a number of spaces (represented here by "␣") and line breaks ("⏎") that all end up as Text nodes in the DOM.

However, for historical reasons not all of the spaces and line breaks in the original markup appear in the DOM. In particular, all the whitespace before head start tag ends up being dropped silently, and all the whitespace after the body end tag ends up placed at the end of the body.

[ from (]

back to DOM: Navigate DOM Tree

Web Scripting Overview

  1. Browser Window Object, DOM
  2. Intro to Event-Based Programing
  3. JavaScript Load Order
  4. What is Live Object
  5. NodeList vs HTMLCollection
  6. DOM: Whitespace Nodes
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Reference
  5. DOM Scripting
  6. SVG
  7. Blog