Open In App

Web API Selection.extend() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The Web Selection API gives developers the ability to recognize the screen regions that the user has now selected and to use code to initiate user selections.

The extend() method moves the focus of the selection of a specific point. This method does not work on anchor elements. The focus will start from the anchor of the element, regardless of the direction.

Syntax:

extend(node, offset)

Parameters:

  • node: This is the node within the focus that will be moved
  • offset: The offset position within the node where the focus will be moved to. This is the optional parameter. This parameter value by default is 0

Return value: undefined

Example 1: Below the example, The focus is moving backward not forward. This example shows moving the focus from one node to the second node.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection extend method</h3>
    <p> Hi <span id="spanID"
        The focus is moving backward in this example
        </span> select this
    </p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
    <script>
        let node = document.getElementById('spanID')
  
        function clickHandler() {
            let selection = window.getSelection();
            let res = selection.extend(node);            
        }
    </script>
</body>
</html>


Output:

Web API Selection.extend() Method

Web API Selection.extend() Method

Example 2: Below the code, The focus will be moving forward not backward. Let’s see the example.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection extend method</h3>
    <p >Select this 
        <span id="spanID"
            The focus will go to forward direction
        </span>
    </p>
    <button type="button" onclick="clickHandler()">
        Focus is moving Forward
    </button>
    <script>
        let node = document.getElementById('spanID')
  
        function clickHandler() {
            let selection = window.getSelection();
            let res = selection.extend(node,1);            
        }
    </script>
</body>
</html>


Output:

Web API Selection.extend() Method

Web API Selection.extend() Method

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

References:  https://developer.mozilla.org/en-US/docs/Web/API/Selection/extend



Last Updated : 10 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads