Course contentsShow
← Web Development
Lesson 667 of 2,98212. The Document Object ModelFree lesson

Text Nodes and Whitespace

How text content becomes nodes in the DOM, including whitespace between elements.

Text Nodes and Whitespace

What You'll Learn

You'll discover how every piece of text—including spaces, tabs, and line breaks—becomes its own node in the DOM tree.

The Surprising Truth About Text

When you write HTML with proper formatting and indentation, every bit of text between tags becomes a text node in the DOM—and that includes whitespace you didn't even think about.

Consider this simple markup:

<div>
  <span>Hello</span>
  <span>World</span>
</div>

You might expect the <div> to have just two children (the two <span> elements), but it actually has five children: a text node (the line break and spaces before the first <span>), the first <span>, another text node (whitespace between spans), the second <span>, and a final text node (the line break and spaces after the second <span>).

Why This Matters

Think of the DOM like a filing system that's extremely literal—it files everything, even the "blank" pages. Every space, tab, and newline character you use for readable code formatting gets preserved as a text node.

This becomes important when you're navigating the DOM or counting child nodes. If you expect an element to have two children but your code finds five, whitespace nodes are often the culprit.

The Practical Impact

Whitespace nodes are usually invisible when rendered (browsers collapse them), but they exist in the DOM structure. When working with the Document Object, you'll need to account for them when traversing between elements or counting nodes.

Key Takeaway: Every character between tags—including spaces, tabs, and newlines used for formatting—creates a text node in the DOM tree, which affects how you navigate and count nodes programmatically.