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

Creating Text Nodes

Create text nodes with document.createTextNode and understand when to use textContent instead.

Creating Text Nodes

You'll learn how to create and insert text content into DOM elements using two different approaches.

What Are Text Nodes?

When you create an element with createElement(), it starts empty. To add text inside it, you have two main options: create a text node with document.createTextNode(), or use the simpler textContent property. Both achieve the same end result, but they work differently under the hood.

The createTextNode Method

document.createTextNode(string) creates a standalone text node—a piece of pure text that exists in the DOM as its own node type. You then need to manually append it to an element:

const paragraph = document.createElement('p');
const textNode = document.createTextNode('Hello, world!');
paragraph.appendChild(textNode);
document.body.appendChild(paragraph);

Think of a text node like a label you print separately, then glue into a folder (the element).

The textContent Shortcut

Most of the time, you'll use textContent instead—it's simpler and more direct:

const paragraph = document.createElement('p');
paragraph.textContent = 'Hello, world!';
document.body.appendChild(paragraph);

Behind the scenes, this creates the text node automatically. It's like writing directly on the folder instead of making a separate label.

When to Use Each

Use createTextNode() when you need precise control over node manipulation or you're building complex structures programmatically. Use textContent for everyday tasks—it's cleaner and more readable.

Key Takeaway: While document.createTextNode() gives you explicit control over text nodes, textContent is usually the simpler, preferred way to add text to elements in modern JavaScript.