You are here: Reference > JavaScript > client-side > HTML DOM > methods > splitText (TextNode)

splitText method (TextNode)

Browser support:
Breaks the current TextNode object into two TextNode objects at the specified index.
The index specifies the character position in the contents of the current TextNode where the split occurs. The first part will be the new content of the current TextNode and a new TextNode object is created from the second part. The new TextNode object is inserted into the document hierarchy as the next sibling of the current TextNode object.
If you want to join adjacent text nodes into a single text node, use the normalize method.

Syntax:

object.splitText (index);
You can find the related objects in the Supported by objects section below.

Parameters:

index
Required in Firefox and Opera, optional in Internet Explorer, Google Chrome and Safari. Zero-based integer that specifies the character position in the contents of the current TextNode at which the split occurs.
The default is zero in Internet Explorer, Google Chrome and Safari. Splitting at the last position is allowed in all browsers, but it is buggy in Internet Explorer (the new TextNode is not inserted into the document hierarchy and its data is undefined, not an empty string).

Return value:

Returns the TextNode object created from the second part.

Example HTML code 1:

This example illustrates the use of the splitText method:
<head>
    <script type="text/javascript">
        function SetBold () {
            var container = document.getElementById ("container");
            var textNode = container.firstChild;
            if (textNode.data.length == 0) {
                return;
            }

            var textNodeRight = textNode.splitText (textNode.data.length - 2);

            var boldTag = document.createElement ("b");
            container.insertBefore (boldTag, textNodeRight);
            boldTag.appendChild (textNodeRight);
        }
    </script>
</head>
<body>
    <div id="container">12345678</div>
    <br />
    <button onclick="SetBold ()">Set the last two non-bold characters to bold</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content