HTML DOM getRangeAt() method

The getRangeAt() method returns the range object which contains startOffset index and endOffset index from the selected text.

Syntax:

range = selection.getRangeAt(index)

Parameters:

  • index: zero-based index from the rangeCount of the document.

Return value:

  • Return the Range object which contain startOffset and endOffset index of selected text.

Example:



In this example, we will select some text and will get range of selected text.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
   <head>
      <title>GeeksforGeeks</title>
      </head>
      <body>
          <h1>GeeksforGeeks</h1>
        <p>select some text and click on
      button to get the range of selection</p>
        <button onclick="range()">Click</button>
      </body>
        <script>
            function range(){
                 let ranges = [];
              sel = window.getSelection();
              for(let i = 0; i < sel.rangeCount; i++) {
               ranges[i] = sel.getRangeAt(i);
               console.log(ranges[i])
              }
              }
        </script>
</html>

chevron_right


Output:

In console, range objects can be seen:

Supported Browsers:

  • Google Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.