Open In App

Web API Selection.removeAllRanges() Method

Last Updated : 29 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Selection API gives developers the ability to recognize the screen regions that the user has now selected and to use code to initiate user selections.

The removeAllRanges() method removes all ranges from the selection. This method leaves the anchor and node properties equal to null and leaves nothing selected.

Syntax:

Selection.removeAllRanges()

Parameter: This method does not have any parameters.

Return Value: This method returns undefined. It does not return any specific value to the caller.

Example 1: It is the basic example illustrating Selection.removeAllRanges() method:

  • index.html

HTML




<html>
  
<head>
    <title>removeAllRanges method </title>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h2>select some text and click the button</h2>
    <button> Click Me </button>
  
    <script>
        var button = document.querySelector('button');
        button.addEventListener("click", () => {
            const selection = window.getSelection();
            selection.removeAllRanges();
        });
    </script>
</body>
  
</html>


Output:

 

Example 2: This is another example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>removeAllRanges method </title>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h2>select <strong>some </strong
          text and <strong>click the </strong>
          button</h2>
    <button> Add Selection </button>
    <button id="removeData"> Remove Selection </button>
  
    <script>
        let button = document.querySelector('button');
        button.addEventListener('click', () => {
            const selection = window.getSelection();
            const strongs = document.getElementsByTagName('strong');
  
  
            for (const node of strongs) {
                const range = document.createRange();
                range.selectNode(node);
                selection.addRange(range);
            }
        });
  
        var button2 = document.getElementById('removeData');
        button2.addEventListener("click", () => {
            var window = document.getSelection();
            window.removeAllRanges();
        });
  
    </script>
</body>
  
</html>


Output:

 

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Selection/removeAllRanges



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads