Open In App

Web API Selection.setBaseAndExtent() Method

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

The setBaseAndExtent() method is used to set the selection to be all the parts or a portion between two specified DOM nodes.

Syntax:

setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset)

Parameters:

  • anchorNode: The initial node of the selection.
  • anchorOffset: The number of children from the anchor node’s root that should not be included in the selection.
  • focusNode: The final node in the selection.
  • focusOffset: The number of children that should be included in the selection starting with the focus node.

Returns: None

Example 1: The following code will select the specified part of the code when the button is pressed.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection setBaseAndExtent method</h3>
    <p>Here is a text 
        <span id="start">START</span
        this will get selected
        <span id="end">END</span
        some more text.
    </p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
    <div id="output"></div>
    <script>
        let startNode = document.getElementById('start')
        let endNode = document.getElementById('end')
  
        function clickHandler() {
            let selection = window.getSelection();
            selection.setBaseAndExtent(startNode, 0, endNode, 0);
            alert(selection.toString());            
        }
    </script>
</body>
  
</html>


Output:

 

Example 2: In the following code, I have set the offset parameters to 2 and 3 respectively to see its effect.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection setBaseAndExtent method</h3>
    <p id="anchor">
        <span>Here </span>
        <span>it </span>
        <span>goes</span>
    </p>
    <p>Some text here</p>
    <p id="focus">
        <span>Now </span>
        <span>it </span>
        <span>ends </span>
    </p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
    <script>
        let anchorNode = document.getElementById('anchor');
        let focusNode = document.getElementById('focus');
  
        function clickHandler() {
            let selection = window.getSelection();
            selection.setBaseAndExtent(anchorNode, 2,
                focusNode, 3);
            alert(selection.toString());
        }
    </script>
</body>
  
</html>


Output:

 

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Selection/setBaseAndExtent



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads