The splitText()
method of the Text
interface breaks the Text
node into two nodes at the specified offset, keeping both nodes in the tree as siblings.
After the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text. The newly created node is returned to the caller. If the original node had a parent, the new node is inserted as the next sibling of the original node. If the offset is equal to the length of the original node, the newly created node has no data.
Separated text nodes can be concatenated using the Node.normalize()
method.
Syntax
newNode = textNode.splitText(offset)
Parameters
-
offset
-
The index immediately before which to break the text node.
Return value
Returns the newly created Text
node that contains the text after the specified offset point.
Exceptions
IndexSizeError
DOMException
-
Thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text.
NoModificationAllowedError
DOMException
-
Thrown if the node is read-only.
Example
In this example, the text of a <p>
is split into two text nodes, and a <u>
is inserted between them.
const p = document.querySelector("p");
const foobar = p.firstChild;
const bar = foobar.splitText(3);
const u = document.createElement("u");
u.appendChild(document.createTextNode(" new content "));
p.insertBefore(u, bar);
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
splitText |
1Before Chrome 30, the offset parameter was optional.
|
12 |
1 |
5 |
≤12.1Before Opera 17, the offset parameter was optional.
|
1The offset parameter is optional.
|
1Before version 4.4, the offset parameter was optional.
|
18Before Chrome 30, the offset parameter was optional.
|
4 |
≤12.1Before Opera 17, the offset parameter was optional.
|
1The offset parameter is optional.
|
1.0Before Samsung Internet 2.0, the offset parameter was optional.
|
See also