Open In App

Web API Selection.removeRange() Method

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Web 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 Selection.removeRange() method removes a range from a selection.

Syntax:

removeRange(range);

Parameters: This method has one parameter only.

  • range:  A range object that will be removed from the selection.

Return value: This method returns undefined.

Example 1: The following code adds some texts and removes the selection by using the removeRange() method.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script>
        var myRange, selection;
        function Add() {
            selection = window.getSelection();
            myRange = document.createRange();
            myRange.selectNodeContents(
                document.getElementById("data"));
            selection.addRange(myRange);
        }
        function remove() {
            selection.removeRange(myRange);
        }
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection removeRange method</h3>
    <h2 id="data"> Select this Text</h2>
    <button onclick="Add();">Add Selection</button>
    <button onclick="remove();">Remove Selection</button>
</body>
  
</html>


Output:

 

Example 2: The following code selects some texts by using the selectNodeContents() method and removes the selection by using the removeRange() method.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        h2 {
            display: inline-block;
        }
    </style>
    <script>
        var myRange, selection;
        function Add() {
            selection = window.getSelection();
            myRange = document.createRange();
            myRange.selectNodeContents(
                document.getElementById("data"));
            selection.addRange(myRange);
        }
        function remove() {
            selection.removeRange(myRange);
        }
  
    </script>
</head>
  
<body>
    <h1 style="color:green;">GeeksforGeeks</h1>
    <h3> Web API selection removeRange method</h3>
    <div>
        <h2 id="data"> Select this Text </h2>
        <h2> | This text not selecting</h2>
    </div>
    <div>
        <button onclick="Add();">Add Selection</button>
        <button onclick="remove();">Remove Selection</button>
    </div>
</body>
  
</html>


Output:

 

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads