Open In App

HTML DOM Range setStart() Method

Last Updated : 12 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The setStart() method is used to set the starting position of a Range. The startNode can be used as a text node, child nodes etc. The startOffset can be the number of characters from the start of startNode or can be the number of child nodes between the start of the startNode.

Syntax:

range.setStart(startNode, startOffset);

Parameters:

  • startNode: The Node which is used to start the range.
  • startOffset: This parameter is Offset index greater than or equal to zero representing the index for the starting of the Range from the startNode.

Return Value: This method does not return any value.

Example 1: In this example, set the starting of range child nodes of a parent node.

This example uses the setStart() method to set the starting child nodes of the range. Here, we have used setEnd() method to set the ending of the range. For clarity of defined range, we have converted the selected range into text using toString() method.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h1>GeeksforGeeks</h1>
    <p id="parent">
        Child 1<br>
        Child 2<br>
    </p>
 
 
    <script>
        const example = document
            .getElementById('parent');
             
        const range = document.createRange();
        range.setStart(example, 0);
        range.setEnd(example, 3);
        console.log(range);
        console.log(range.toString());
    </script>
</body>
 
</html>


 Output: In console, the created range can be seen.

Example 2: In this example, set the starting of range by getting characters of a text node.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <p id="example">
        Characters of this node will
        be used to set the range.
    </p>
 
 
    <script>
        const example = document
            .getElementById('example');
 
        const textNode = example.childNodes[0];
        const range = document.createRange();
 
        // Starting of range will
        // be 0th character
        range.setStart(textNode, 0);
 
        // Ending of range will be
        // 54th character
        range.setEnd(textNode, 54);
        console.log(range);
        console.log(range.toString())
    </script>
</body>
 
</html>


Output: In console, the created range can be seen.

Supported Browsers:

  • Google Chrome 1
  • Edge 12
  • Firefox 1
  • Safari 1
  • Opera 9
  • Internet Explorer 9


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads