Open In App

HTML DOM getRangeAt() method

Improve
Improve
Like Article
Like
Save
Share
Report

The getRangeAt() method returns the range object which contains the 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 contains the startOffset and endOffset index of the selected text.

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

HTML




<!DOCTYPE html>
<html lang="en">
 
<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>
 
    <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>
   
</body>
 
</html>


Output: In the console, range objects can be seen:

Supported Browsers:

  • Google Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

Last Updated : 21 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads