W3cubDocs

/DOM

Text.splitText

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.

Syntax

replacementNode = textnode.splitText(offset) 

Example

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>

Specifications

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 1
1
Before Chrome 30, the offset argument was optional.
Yes 1 Yes Yes
Yes
Before Opera 17, the offset argument was optional.
Yes
Yes
The offset argument is optional.
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support Yes
Yes
Before version 4.4, the offset argument was optional.
18
18
Before Chrome 30, the offset argument was optional.
? 4 Yes
Yes
Before Opera 17, the offset argument was optional.
Yes
Yes
The offset argument is optional.
?

See also

© 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