Sunday, November 17, 2024
Google search engine
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

Most Popular

Recent Comments