Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWeb API Selection.type Property

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.

  • 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">neveropen</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">neveropen</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:

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments