Open In App

Web API Selection addRange() Method

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 addRange() method adds a range to the selection.

Syntax:



addRange(range);

Parameters:

Return value: This method does not return any specific value.



Example 1: The following code selects some text using the addRange() method and removes the text by using the remove button.




<!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 addrange 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 only strong tags by using the addRange() method.




<!DOCTYPE html>
<html>
   
<head
    <script>
        var range,selection,strongs ;
        function Add(){
            selection =  window.getSelection() ;
            strongs = document.getElementsByTagName('strong');
 
            for(const node of strongs){
                  range = document.createRange();
                  range.selectNode(node);
                  selection.addRange(range);
             }
        }       
        function remove(){
          if (selection.rangeCount > 0) {
                  selection.removeAllRanges();
              }
        }
    </script>
</head>
   
<body>
    <h1 style="color:green;">GeeksforGeeks</h1>
    <h3> Web API selection addRange method</h3>
    <h2 id="data">
        Hi I am a <strong>Programmer</strong>
        and <strong >GFG Writer</strong></h2>
    <button onclick="Add();">Add Selection</button>
    <button onclick="remove();">Remove Selection</button>
</body>
   
</html>

Output:

 

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


Article Tags :