Open In App

Web API Selection.rangeCount Property

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

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.

  • rangeCount read-only property tells number of ranges in the selection. Before the user has clicked on the page, the rangeCount is 0. When the user clicks , the value of rangeCount is 1, even if no selection is made. A user can select one range at a time, so the rangeCount is frequently 1.  Browsers also support multiple selections across table.

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

HTML




<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




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

 

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads