Open In App

Web API Selection.rangeCount Property

Web Selection API 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 rangeCount.



Example 1: This example shows the basic usage of rangeCount property.




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

Output:

 

Example 2: In this example, we will disable the selection of multiple ranges using removeRange() method. You will not be able to select text more than once.




<html>
  
<body>
      <h1 style="color:green">GeeksforGeeks</h1>
      <h3> Web API Selection.rangeCount property </h3>
   
     <script>    
        document.onselectionchange = () => {
              let s = document.getSelection();
            console.log(s.rangeCount)
            if (s.rangeCount > 1) {
               s.removeRange(s.getRangeAt(1));
              }
            }
   </script>
</body>
</html>

Output: 

 

 


Article Tags :