JavaScript Text splitText() Method

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

What You’ll Learn

Text.splitText() is an instance method that breaks one text node into two sibling Text nodes at a given offset. Learn the return value, how to insert an element between the halves, how normalize() joins them again, and common errors—with five examples and try-it labs.

01

Kind

Instance method

02

Returns

New Text node

03

Argument

offset index

04

Tree effect

Two sibling nodes

05

Opposite

normalize()

06

Status

Baseline widely

Introduction

Sometimes you need a “cut” in the middle of a text node—so you can wrap part of the text, highlight a word, or insert a node between two halves. You cannot put an element inside a Text node. Instead, you split the text, then insert between the two resulting siblings.

JavaScript
const text = new Text("foobar");
const second = text.splitText(3);
console.log(text.data);   // "foo"
console.log(second.data); // "bar"
💡
Beginner tip

MDN: separated text nodes can be concatenated again with Node.normalize(). Think of splitText and normalize as opposite operations.

Understanding the Method

MDN: splitText() breaks the Text node into two nodes at the specified offset, keeping both nodes in the tree as siblings. After the split:

  • Original node — keeps content up to the offset.
  • New node — holds the remaining text; this is the return value.
  • Parent — if present, the new node is inserted as the next sibling.
  • Offset === length — the new node has empty data.

📝 Syntax

JavaScript
const after = textNode.splitText(offset);

Parameters

NameTypeDescription
offsetNumberIndex immediately before which to break the text node (0-based, like string indices for BMP characters).

Return value

The newly created Text node that contains the text after the offset.

Exceptions

  • IndexSizeErroroffset is negative or greater than the number of 16-bit units in the node’s text.
  • NoModificationAllowedError — the node is read-only.

🔄 splitText() vs normalize()

splitText(offset)normalize()
EffectOne Text → two siblingsAdjacent Text siblings → one
ReturnsNew Text (after offset)undefined
Called onA Text nodeUsually a parent / ancestor Node
Typical useCut so you can insert betweenTidy the tree after edits

After a split, wholeText on either sibling still reads the full adjacent run until you insert a non-Text node between them.

⚡ Quick Reference

GoalCode
Split at index 3const after = text.splitText(3)
Left halftext.data (original node)
Right halfafter.data
Insert betweenparent.insertBefore(el, after)
Merge againparent.normalize()
MDN statusBaseline Widely available (Jul 2015)

🔍 At a Glance

Four facts about splitText().

Kind
method

On Text

Returns
Text

After offset

Arg
offset

Break index

Status
baseline

Widely available

Examples Gallery

Examples follow MDN Text.splitText() and everyday insert-between patterns.

📚 Getting Started

Split one node and inspect both halves.

Example 1 — Split "foobar" at 3

Classic cut: left keeps foo, return value is bar.

JavaScript
const text = new Text("foobar");
const bar = text.splitText(3);

console.log(text.data);  // "foo"
console.log(bar.data);   // "bar"
console.log(bar instanceof Text);
Try It Yourself

How It Works

Offset 3 means “break before index 3.” Characters 0–2 stay on the original node; the rest move to the returned Text.

Example 2 — New Node Becomes Next Sibling

When the text has a parent, the returned node is inserted after it.

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

const bar = foobar.splitText(3);

console.log(p.childNodes.length);     // 2
console.log(p.firstChild.data);       // "foo"
console.log(p.lastChild.data);        // "bar"
console.log(p.lastChild === bar);     // true
console.log(foobar.nextSibling === bar);
Try It Yourself

How It Works

You do not need a separate appendChild for the second half—the split inserts it for you when a parent exists.

📈 Insert Between, Edge Cases & Undo

The MDN pattern and how to merge again.

Example 3 — MDN: Insert an Element Between Halves

Split, then insertBefore the returned node.

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

const foobar = p.firstChild;
const bar = foobar.splitText(3);

const u = document.createElement("u");
u.appendChild(new Text(" new content "));
p.insertBefore(u, bar);

console.log(p.innerHTML);
// foo<u> new content </u>bar
Try It Yourself

How It Works

Matches the MDN example: bar is the insertion reference, so the new <u> lands between foo and bar.

Example 4 — Offset Equal to Length

Splitting at the end returns an empty Text sibling.

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

const empty = text.splitText(text.length);

console.log(text.data);                 // "Hi"
console.log(JSON.stringify(empty.data)); // ""
console.log(p.childNodes.length);       // 2
console.log(empty.length);              // 0
Try It Yourself

How It Works

Per MDN, when offset equals the original length, the new node has no data. An offset greater than length throws IndexSizeError.

Example 5 — Undo with normalize()

Split creates two siblings; normalize merges them back.

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

text.splitText(4);
console.log(div.childNodes.length); // 2
console.log(div.firstChild.wholeText); // "CodeToFun"

div.normalize();
console.log(div.childNodes.length); // 1
console.log(div.firstChild.data);   // "CodeToFun"
Try It Yourself

How It Works

After the split, wholeText still shows the full run. normalize() collapses the siblings into one Text node again.

🚀 Common Use Cases

  • Inserting a mark, link, or underline in the middle of a text node.
  • Building rich-text style edits without replacing the whole parent via innerHTML.
  • Teaching how Text siblings relate to wholeText and normalize().
  • Unit tests that assert DOM structure after a cut.
  • Preparing two anchors so insertBefore has a clear reference node.

🔧 How It Works

1

Call splitText(offset)

Engine validates the offset against the text length.

Call
2

Trim the original node

Keeps characters before the offset.

Left
3

Create & insert the rest

New Text holds the remainder; next sibling if parented.

Right
4

Return the new Text

Use it as insertBefore reference or read its data.

📝 Notes

  • Baseline Widely available (MDN, since July 2015).
  • Not Deprecated, Experimental, or Non-standard — no status banner required.
  • Offset is counted in UTF-16 code units (same idea as string indices for many BMP characters).
  • Opposite cleanup: normalize().
  • Related: wholeText, Text(), insertBefore(), JavaScript hub.

Universal Browser Support

Text.splitText() is Baseline Widely available across modern browsers (MDN: since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

Text.splitText()

Split a text node at an offset into two sibling Text nodes — great for mid-text inserts.

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 Supported in modern IE versions
Supported
splitText() Excellent

Bottom line: Use splitText(offset) to cut a Text node, insertBetween with insertBefore(returnedNode), and normalize() to merge adjacent text again.

Conclusion

text.splitText(offset) cuts a text node into two siblings and returns the second half—perfect for inserting elements mid-string. Pair it with insertBefore, and use normalize() when you want one text node again.

Continue with availHeight, normalize(), wholeText, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Keep the returned node as your insertBefore reference
  • Check 0 <= offset <= text.length before splitting
  • Call normalize() when you no longer need the cut
  • Use wholeText to verify adjacent runs after a split
  • Prefer DOM methods over innerHTML for mid-text wraps

❌ Don’t

  • Pass a negative offset or one past length
  • Expect to nest an element inside a Text node without splitting
  • Forget the new node is already in the tree when a parent exists
  • Confuse splitText with String.prototype.split
  • Leave many empty text siblings if you can normalize instead

Key Takeaways

Knowledge Unlocked

Five things to remember about splitText()

Cut a Text node; insert between the halves.

5
Core concepts
📄 02

Returns Text

after the cut

Result
📌 03

Next sibling

when parented

DOM
⚖️ 04

Opposite

normalize()

Pair
🎯 05

Baseline

widely available

Status

❓ Frequently Asked Questions

It breaks the Text node into two sibling Text nodes at the given offset. The original keeps the text before the offset; the method returns a new Text node with the rest. If the original had a parent, the new node is inserted as the next sibling.
No. MDN marks Text.splitText() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
The index immediately before which to break. splitText(3) on "foobar" leaves "foo" in the original node and returns a node with "bar".
IndexSizeError if offset is negative or greater than the node’s length (16-bit units). NoModificationAllowedError if the node is read-only.
Call parent.normalize() (or normalize on an ancestor). MDN describes Node.normalize() as the opposite: it merges adjacent text nodes again.
The original keeps all characters; the returned Text node has empty data (""), and is still inserted as the next sibling when a parent exists.
Did you know?

String.prototype.split returns an array of strings and does not change the DOM. Text.splitText mutates the live document tree. Same English word, completely different APIs.

Next: Screen.availHeight

Learn the available screen height in CSS pixels.

availHeight →

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