Open In App

HTML DOM splitText() method

Last Updated : 21 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The splitText() method breaks the Text node into two nodes at the specified offset index, keeping both nodes in the tree as siblings.

After Splitting the text, the main node contains all the content up to the specified offset index point, and a newly created node of the same type contains the remaining text.

Syntax:

newTextNode=textNode.splitText(offsetIndex)

Parameters:

  • offset index: The index immediately before which to break the text node.

Return Value:

  • Returns the newly created Text node that contains the text after the offset index.

Example: In this example, we will see the use of splitText() method.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
          HTML DOM textSplit() method
      </title>
</head>
 
<body>
    <p id="h">GeeksforGeeks</p>
   
    <script>
        // get the p element
        const a = document.getElementById('h');
       
        // get the textcontent in textnode
        const firstNode = a.firstChild;
       
        // splitting the firstnode at 5th offset index
        const newNode = firstNode.splitText(5);
        console.log(firstNode);
        console.log(newNode);
    </script>
   
</body>
 
</html>


Output: In the console, the two splitted text Nodes can be seen.

Supported Browsers:

  • Google Chrome
  • Edge
  • Firefox
  • Opera

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads