JavaScript Text Constructor

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

What You’ll Learn

The Text() constructor builds a DOM text node. Learn optional string content, how it compares to document.createTextNode(), how to insert it with appendChild(), and how to read or update the text—with five examples and try-it labs.

01

Create

new Text()

02

Returns

Text node

03

Argument

optional string

04

Default

empty string

05

Twin

createTextNode

06

Status

Baseline widely

Introduction

In the DOM, the letters you see inside an element are often stored in a Text node—not as a property of the element alone. When the browser parses <p>Hello</p>, it creates an element and a child text node whose data is "Hello".

new Text("Test") lets you build that kind of node yourself, then attach it with appendChild, insertBefore, or similar APIs.

JavaScript
const text = new Text("Test");
console.log(text.data); // "Test"
💡
Beginner tip

Creating a Text node does not show anything on screen. You must insert it into a parent that is already (or later becomes) in the document.

Understanding the Text() Constructor

MDN: the Text() constructor returns a new Text object with the optional string given in the parameter as its textual content.

  • Constructor — call with new Text(...).
  • Optional string — the node’s initial text.
  • Empty default — no argument means "".
  • CharacterData family — Text inherits data APIs (like data, length).
  • Node family — also a Node (nodeType === 3).

📝 Syntax

JavaScript
new Text()
new Text(string)

Parameters

NameTypeDescription
stringString (optional)Textual content of the new text node. Omit for an empty node.

Return value

A new Text object whose content is the string parameter, or the empty string if no parameter was given.

🔄 new Text() vs createTextNode()

Both produce a Text node. Choose either style—know both so you can read older tutorials that only show document.createTextNode.

JavaScript
const a = new Text("Hello");
const b = document.createTextNode("Hello");

console.log(a.data === b.data);           // true
console.log(a.nodeType === Node.TEXT_NODE); // true
console.log(b.nodeType === 3);            // true
When to prefer which

Use new Text() when you want a clear constructor style. Use document.createTextNode() when matching Document factory patterns already in a codebase. For setting lots of text on an element, often element.textContent = "..." is simpler than building nodes by hand.

📄 Reading and Updating Text

PropertyWhat beginners use it for
dataCharacterData string stored in the text node
nodeValueSame string via the Node API
textContentAlso the text for a Text node
lengthNumber of characters in data
nodeNameAlways "#text" for text nodes
nodeType3 / Node.TEXT_NODE

⚡ Quick Reference

GoalCode
Create with textnew Text("Test")
Empty text nodenew Text()
Read contenttext.data or text.nodeValue
Insert into DOMparent.appendChild(text)
Classic twindocument.createTextNode("Test")
MDN statusBaseline Widely available (Oct 2017)

🔍 At a Glance

Four facts about new Text().

Kind
constructor

Web API

Returns
Text

DOM text node

Arg
string?

optional

Status
baseline

Widely available

Examples Gallery

Examples follow MDN Text() and everyday DOM patterns for inserting and inspecting text nodes.

📚 Getting Started

Create Text nodes and inspect their content.

Example 1 — MDN-Style new Text("Test")

Build a text node with an initial string.

JavaScript
const text = new Text("Test");
console.log(text.data);
console.log(text.nodeName);
console.log(text.nodeType);
console.log(text instanceof Text);
Try It Yourself

How It Works

The constructor returns a live Text object. data holds "Test"; nodeType is 3 for text nodes.

Example 2 — Empty Text Node

Omit the argument to get an empty string as content.

JavaScript
const empty = new Text();
console.log(JSON.stringify(empty.data));
console.log(empty.length);
console.log(empty.data === "");
Try It Yourself

How It Works

Per MDN, no parameter means empty content. You can still assign empty.data = "later" before or after inserting the node.

📈 Insert, Compare & Update

Use Text nodes with the rest of the DOM API.

Example 3 — Append to an Element

Creating is step one; appending makes the text visible.

JavaScript
const p = document.createElement("p");
const text = new Text("CodeToFun");
p.appendChild(text);

console.log(p.textContent);
console.log(p.firstChild.nodeName);
console.log(p.childNodes.length);
Try It Yourself

How It Works

p.textContent reads descendant text. The only child is your #text node. See also appendChild().

Example 4 — Same Result as createTextNode

Constructor and Document factory produce matching content.

JavaScript
const viaCtor = new Text("Hello");
const viaDoc = document.createTextNode("Hello");

console.log(viaCtor.data === viaDoc.data);
console.log(viaCtor.nodeType === viaDoc.nodeType);
console.log(viaCtor instanceof Text && viaDoc instanceof Text);
Try It Yourself

How It Works

Both paths return Text instances. Prefer one style in a given file for consistency.

Example 5 — Update data After Insert

Mutate the text node; the parent’s visible text updates.

JavaScript
const span = document.createElement("span");
const text = new Text("Hi");
span.appendChild(text);

text.data = "Hello, CodeToFun";
console.log(span.textContent);
console.log(text.length);
Try It Yourself

How It Works

Assigning data changes the CharacterData content in place. You do not need to create a new Text node for a simple string update.

🚀 Common Use Cases

  • Building DOM trees without HTML string parsing.
  • Unit tests that assert on real Text nodes.
  • Inserting text beside elements without wiping siblings via innerHTML.
  • Learning how browsers store text under elements.
  • Migrating mental model from createTextNode to constructors.

🔧 How It Works

1

Call new Text(string?)

Engine allocates a Text node; data is the string or "".

Create
2

Node is detached

It has no parent until you insert it into the tree.

Detached
3

appendChild / insertBefore

Parent gains a #text child; text can become visible.

Insert
4

Read or mutate data

Use data / nodeValue / textContent as needed.

📝 Notes

Universal Browser Support

The Text() constructor is Baseline Widely available across modern browsers (MDN: since October 2017). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

Text() constructor

Create DOM text nodes with an optional string — pair with appendChild to show them.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Prefer createTextNode on very old IE
Limited
Text() Excellent

Bottom line: Use new Text(string) or document.createTextNode(string); both create Text nodes. Prefer element.textContent for simple whole-element text updates.

Conclusion

new Text(string) builds a DOM text node with optional content. Append it to show text, or use createTextNode / textContent when that fits your code better.

Continue with assignedSlot, textContent, appendChild(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Remember to appendChild (or insert) before expecting visible text
  • Use data / nodeValue to update an existing text node
  • Prefer textContent when replacing an element’s entire text
  • Pick one creation style per file (new Text or createTextNode)
  • Call normalize() if you create many adjacent text siblings

❌ Don’t

  • Expect new Text("Hi") alone to change the page
  • Confuse Text nodes with HTMLElement nodes
  • Use innerHTML just to add plain text (XSS risk if untrusted)
  • Assume every child of an element is an Element—often it is #text
  • Forget empty new Text() is valid and useful as a placeholder

Key Takeaways

Knowledge Unlocked

Five things to remember about Text()

Construct text nodes, then insert them.

5
Core concepts
📄 02

Returns Text

nodeType 3

Result
🔄 03

Twin

createTextNode

Alt
📤 04

Insert

appendChild

DOM
🎯 05

Baseline

widely available

Status

❓ Frequently Asked Questions

new Text() or new Text(string) returns a new Text (DOM text) node. If you pass a string, that becomes the node’s textual content; if you omit it, the content is the empty string.
No. MDN marks the Text() constructor as Baseline Widely available (since October 2017). It is not Deprecated, Experimental, or Non-standard.
Both create Text nodes. document.createTextNode(data) is the classic Document method; new Text(string) is the modern constructor. For everyday code either is fine—many tutorials still show createTextNode.
No. Creating a Text node only builds an object. Append it with parent.appendChild(text) (or similar) before it appears in the document.
Text nodes have nodeType 3 (Node.TEXT_NODE) and nodeName "#text". You can also read the string via data, nodeValue, or textContent.
Yes. Assign to text.data, text.nodeValue, or text.textContent after the node exists—including after it is in the DOM.
Did you know?

Whitespace in HTML often becomes text nodes too. That is why element.childNodes can list more nodes than element.children—the latter lists only element children, skipping #text.

Next: Text.assignedSlot

Learn which Shadow DOM slot a text node is assigned to.

assignedSlot →

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.

5 people found this page helpful