JavaScript Document createTextNode() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createTextNode() is an instance method that creates a new Text node (see MDN Document: createTextNode()). Learn the data parameter, how Text nodes escape HTML characters, how to append them, how they differ from innerHTML, and five try-it labs.

01

Kind

Instance method

02

Args

data (string)

03

Returns

Text node

04

nodeType

3 (TEXT_NODE)

05

Safety

Escapes HTML

06

Status

Baseline

Introduction

Almost every visible string on a web page lives inside a Text node — the characters between tags. When you write <p>Hello</p>, the word Hello is a Text node child of the paragraph.

document.createTextNode(data) builds that kind of node in JavaScript. MDN also notes an important safety tip: this method can be used to escape HTML characters. If the string contains < or &, they stay as text instead of becoming markup.

💡
Create → append

1) const text = document.createTextNode("Hello")
2) element.appendChild(text) (MDN pattern)
3) The string appears as plain text in the page

Related tutorials: createElement(), createComment(), textContent.

Understanding document.createTextNode()

An instance method on Document (usually document.createTextNode(...) on the live page).

  • data — string put into the Text node (MDN).
  • Return value — a new Text node (MDN).
  • HTML escaping — MDN: can escape HTML characters (safe plain text).
  • nodeTypeNode.TEXT_NODE (3).
  • Read backtext.data, text.nodeValue, or text.textContent.
  • Attach — use appendChild, append, or insertBefore.

📝 Syntax

General form of Document.createTextNode (MDN):

JavaScript
createTextNode(data)

Parameters

  • data — a string containing the data to put in the text node (MDN).

Return value

A Text node (MDN).

Exceptions

None listed for createTextNode() on MDN.

MDN example

Buttons append their labels into a paragraph as Text nodes:

JavaScript
function addTextNode(text) {
  const newText = document.createTextNode(text);
  const p1 = document.getElementById("p1");
  p1.appendChild(newText);
}

document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    addTextNode(`${event.target.textContent} `);
  });
});

⚡ Quick Reference

GoalCode
Create textconst t = document.createTextNode("Hi")
Appendel.appendChild(t)
Read datat.data or t.nodeValue
nodeTypeNode.TEXT_NODE (3)
Safe user stringel.appendChild(document.createTextNode(userInput))
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createTextNode().

Returns
Text

node

Arg
data

string

Escapes
HTML chars

MDN

Status
Baseline

since 2015

📋 Detached Text vs appended Text

After createTextNodeAfter appendChild
In the document tree?No (detached)Yes
Visible on the page?NoYes (as text)
Typical next stepInspect dataUser sees the string

Examples Gallery

Examples follow MDN Document: createTextNode() and practical Text-node patterns for beginners.

📚 Getting Started

Create Text nodes and append them safely.

Example 1 — MDN: append button labels

Each click creates a Text node and appends it to a paragraph.

JavaScript
function addTextNode(text) {
  const newText = document.createTextNode(text);
  document.getElementById("p1").appendChild(newText);
}

// Click "YES!" → appends "YES! " as plain text
addTextNode("YES! ");
console.log(document.getElementById("p1").textContent);
Try It Yourself

How It Works

MDN’s helper creates a Text node from a string, then appendChild attaches it to #p1.

Example 2 — Escape HTML characters (MDN)

Angle brackets stay visible as text — they are not parsed as tags.

JavaScript
const box = document.getElementById("safe");
const risky = "<img src=x onerror=alert(1)>";

box.appendChild(document.createTextNode(risky));

console.log(box.childNodes[0].nodeName); // "#text"
console.log(box.textContent);            // shows the <img ...> string literally
Try It Yourself

How It Works

MDN: createTextNode can escape HTML characters. The string becomes a Text node, not an element — safer than assigning untrusted HTML to innerHTML.

📈 Practical Patterns

Inspect properties and build small DOM trees.

Example 3 — data, nodeType, and instanceof

Confirm you created a real Text node.

JavaScript
const t = document.createTextNode("CodeToFun");

console.log(t.data);                              // "CodeToFun"
console.log(t.nodeType);                          // 3
console.log(t.nodeType === Node.TEXT_NODE);       // true
console.log(t instanceof Text);                   // true
Try It Yourself

How It Works

data holds the string. TEXT_NODE is always 3 for Text nodes.

Example 4 — Build an element with a Text child

Combine createElement and createTextNode.

JavaScript
const li = document.createElement("li");
const label = document.createTextNode("Learn createTextNode");
li.appendChild(label);

document.getElementById("list").appendChild(li);
console.log(li.textContent); // "Learn createTextNode"
Try It Yourself

How It Works

Elements hold structure; Text nodes hold characters. Building both explicitly is a classic DOM pattern (and what many frameworks do under the hood).

Example 5 — createTextNode vs innerHTML

Same string, two very different results.

JavaScript
const raw = "<strong>Bold?</strong>";

const a = document.getElementById("as-text");
const b = document.getElementById("as-html");

a.appendChild(document.createTextNode(raw));
b.innerHTML = raw;

console.log(a.childElementCount); // 0 (only a Text node)
console.log(b.childElementCount); // 1 (<strong> element)
Try It Yourself

How It Works

Text nodes never parse tags. innerHTML does. Prefer Text nodes (or textContent) for untrusted strings.

🚀 Common Use Cases

  • Safe user content — show names, comments, or search terms without parsing HTML (MDN escape note).
  • Building lists and labels — pair with createElement.
  • Incremental appends — MDN button demo adds text over time.
  • Editors / Ranges — insert Text nodes at a caret.
  • Teaching the DOM — contrast Text vs Element vs Comment.
  • Whitespace control — create exact spaces or empty text nodes when needed.

🧠 How createTextNode() Works

1

Pass a data string

MDN: one string argument for the Text node contents.

Input
2

Get a Text node

Characters are stored as text — not parsed as HTML (MDN).

Create
3

Append into the tree

Use appendChild / append like MDN’s example.

Attach
4

Plain text appears

Users see the string; markup characters stay escaped as text.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • Creates a new Text node from a data string (MDN).
  • Can be used to escape HTML characters (MDN).
  • nodeType is 3 (TEXT_NODE).
  • Detached until you append or insert it.
  • Related: createElement(), createComment(), textContent.

Browser Support

Document.createTextNode() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createTextNode()

Create Text nodes for safe plain-text DOM content across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createTextNode() Wide

Bottom line: Use createTextNode(data) for plain text (and HTML-escaping). Append the Text node into an element to show it on the page.

Conclusion

document.createTextNode(data) builds a Text node from a string. MDN highlights that it can escape HTML characters — ideal for inserting plain text safely. Create the node, append it, and you have reliable text in the DOM.

Continue with createRange(), createTouch(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use Text nodes for untrusted or user-provided strings (MDN escape tip)
  • Append with appendChild / append
  • Pair with createElement when building structure
  • Check nodeType === Node.TEXT_NODE while learning
  • Prefer textContent when you only need to replace all text

❌ Don’t

  • Put untrusted HTML into innerHTML when Text would do
  • Expect a detached Text node to appear without appending it
  • Confuse Text nodes with Comment or Element nodes
  • Assume createTextNode parses tags (it does not)
  • Forget spaces when concatenating multiple Text appends

Key Takeaways

Knowledge Unlocked

Five things to remember about createTextNode()

Create plain-text DOM nodes safely.

5
Core concepts
📄02

Arg

data

string
🛡03

Escapes

HTML chars

MDN
04

Attach

appendChild

MDN
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createTextNode() creates a new Text node. Pass a string (data) and you get a Text node you can append into the DOM.
No. MDN marks Document.createTextNode() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A Text node (MDN). Read text.data, text.nodeValue, or text.textContent for the string.
MDN notes this method can be used to escape HTML characters. Characters like < and & stay as plain text — they are not parsed as markup (unlike innerHTML).
Node.TEXT_NODE, which equals 3. You can also use text instanceof Text.
Use createTextNode when you need an actual Text node to insert, move, or split. Assigning element.textContent is shorter when you only want to replace all text inside an element.
Did you know?

You can also write new Text("Hello") in modern browsers. The classic document.createTextNode("Hello") factory is what MDN documents and what you will see most often in tutorials and older codebases.

Next: createTouch()

Learn the deprecated non-standard Touch factory and why MDN prefers TouchEvent().

createTouch() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful