Syntax
js
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
IndexSizeErrorDOMException-
Thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text.
NoModificationAllowedErrorDOMException-
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.
html
<p>foobar</p>
js
const p = document.querySelector("p");
// Get contents of <p> as a text node
const foobar = p.firstChild;
// Split 'foobar' into two text nodes, 'foo' and 'bar',
// and save 'bar' as a const
const bar = foobar.splitText(3);
// Create a <u> element containing ' new content '
const u = document.createElement("u");
u.appendChild(document.createTextNode(" new content "));
// Add <u> before 'bar'
p.insertBefore(u, bar);
// The result is: <p>foo<u> new content </u>bar</p>
Specifications
| Specification |
|---|
| DOM # ref-for-dom-text-splittextâ‘ |
Browser compatibility
See also
- The
Textinterface it belongs to. - The opposite method:
Node.normalize.