Thursday, June 11, 2026
HomeLanguagesJavascriptWeb API Selection.rangeCount Property

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.

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

 

 

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

3 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS