Open In App

Web API Selection.toString() Method

The 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 toString() method is used to get a string representation of the selected text.



Syntax:

toString()

Parameters: None



Returns: A string representing the selection.

Example 1: In this example, we will see the basic use of the toString method.




<!DOCTYPE html>
<html>
  
<head></head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection toString method</h3>
    <p>
        Here is some text. Some more text. Some more text.
    </p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
    <div id="output"></div>
    <script>
  
        function clickHandler() {
            let selection = window.getSelection();
            alert(selection.toString());
        }
    </script>
</body>
  
</html>

Output:

Web API Selection.toString() Method

Example 2: In this example, all the text on the screen will be selected and the text will be alerted to the user.




<!DOCTYPE html>
<html>
  
<head></head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection toString method</h3>
    <p>
        <span id="start">START</span>
        this will get selected
        <span id="end">END</span>
    </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, 1);
            alert(selection.toString());
        }
    </script>
</body>
  
</html>

Output:

Web API Selection.toString() Method

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


Article Tags :