Open In App

Web API Selection.type Property

Web API Selection.type is used to get the range of text selected by the user or the position of the caret . The window.getSelection() is used to get the selection object. 

Syntax:



let selection = window.getSelection( );

It comes with some instance properties and one among them is type.

Selection.type: It is a read-only property that tell the type of selection done by the user. It has 3 possible values.



Example 1: In this example, we will detect the type of selection and print it using Selection.type. To detect the type of selection, we will make use of selectionchange event. The output shows all the three values of type property. When you deselect something, it returns “none”. When you deselect something that is selected, it returns “caret” value.  When you select the range of characters, it returns “range” value.




<html>
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3>  Web API Selection.type property </h3>
    <script>    
        document.onselectionchange = () => {
            let selection = document.getSelection();
            console.log(selection.type);
        };
    </script>
</body>
</html>

Output: 

 

Example 2: In this example , we will delete the selected text from the document and print it on console for better understanding.




<html>
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3>  Web API Selection.type property </h3>
    <script>    
        document.onselectionchange = () => {
            let selection = document.getSelection();
            console.log(selection.toString())
            selection.deleteFromDocument();
        };
    </script>
</body>
</html>

Output:

 


Article Tags :