Open In App

Web API Selection.type Property

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

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.

  • none: No selection is done 
  • caret: When the selection is collapsed or the caret is placed at the point of selection.
  • range: When a range of characters is selected.

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




<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




<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:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads