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:
- range: This method has only one parameter. This range parameter is added to the selection.
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.
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;">          neveropen      </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.
HTML
<!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;">neveropen</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

… [Trackback]
[…] Find More Info here on that Topic: geeksforgeeks.org/web-api-selection-addrange-method-2/ […]
… [Trackback]
[…] Find More on that Topic: geeksforgeeks.org/web-api-selection-addrange-method-2/ […]