The Text.splitText()
method 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.
A DOMException
with a value of INDEX_SIZE_ERR
is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a DOMException
with a value of NO_MODIFICATION_ALLOWED_ERR
is thrown if the node is read only.
replacementNode = textnode.splitText(offset)
In this example, a <p>
text node will be split into two text nodes and a <span>
inserted between them.
<body> <p id="p">foobar</p> <script type="text/javascript"> var p = document.getElementById('p'); var textnode = p.firstChild; // split between foo and bar var replacementNode = textnode.splitText(3); // creating a span with ' span contents ' var span = document.createElement('span'); span.appendChild(document.createTextNode(' span contents ')); // adding the span before 'bar' p.insertBefore(span, replacementNode); // the result is <p id="p">foo<span> span contents </span>bar</p> </script> </body>
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Text.splitText' in that specification. | Living Standard | No change from Document Object Model (DOM) Level 3 Core Specification. |
Document Object Model (DOM) Level 3 Core Specification The definition of 'Text.splitText' in that specification. | Obsolete | No change from Document Object Model (DOM) Level 2 Core Specification. |
Document Object Model (DOM) Level 2 Core Specification The definition of 'Text.splitText' in that specification. | Obsolete | No change from Document Object Model (DOM) Level 1 Specification. |
Document Object Model (DOM) Level 1 Specification The definition of 'Text.splitText' in that specification. | Obsolete | Initial definition. |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 1
|
Yes | 1 | Yes | Yes
|
Yes
|
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes
|
18
|
? | 4 | Yes
|
Yes
|
? |
Text
interface it belongs to.Node.normalize
.
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Text/splitText