Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptHTML DOM Range setEnd() Method

HTML DOM Range setEnd() Method

The setEnd() method is used to set the ending position of a Range.

The endNode can be used as a text node, child nodes etc. The endOffset can be the number of characters from the endNode or can be the number of child node of the endNode.

Syntax:

range.setEnd(endNode, endOffset);

Parameters: This method accepts two parameters as mentioned above and described below:

  • endNode: The Node which is used to set the ending of the range.
  • endOffset: This parameter is Offset index greater than or equal to zero representing the index for the ending of the Range.

Return Value: This method does not return any value.

Example 1: This example setting ending of range as child nodes of a parent node.

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

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        HTML DOM range setEnd() method
    </title>
</head>
 
<body>
    <h1>neveropen</h1>
 
    <p id="exampleNode">
        Child 1<br>
        Child 2<br>
    </p>
 
 
    <script>
        const exampleNode = document
            .getElementById('exampleNode');
 
        const range = document.createRange();
 
        // 0th child gets at starting
        // of the range
        range.setStart(exampleNode, 0);
 
        // 3rd child gets at ending
        // of the range
        range.setEnd(exampleNode, 3);
        console.log(range);
        console.log(range.toString());
    </script>
</body>
 
</html>


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

Example 2: This example setting the ending of range as characters of a text node.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        HTML DOM range setEnd() method
    </title>
</head>
 
<body>
    <h1>neveropen</h1>
 
    <p id="exampleNode">
        Characters of this node will
        be used to set the range.
    </p>
 
 
    <script>
        const exampleNode = document
            .getElementById('exampleNode');
 
        const textNode = exampleNode.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

RELATED ARTICLES

Most Popular

Recent Comments