Open In App

Web API Selection.modify() 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 modify() method alters the current selection or cursor position by employing short text commands.



Syntax:

modify(alter, direction, granularity)

Parameters:



Returns:  None

Example 1: This example will show the forward extension of the selection.




<!DOCTYPE html>
<html>
  
<head>
    <title>Web API</title>
</head>
  
<body>
    <script>
        function clickHandler() {
            let selection = window.getSelection();
            selection.modify('extend', 'forward', 'word');
        }
    </script>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection modify method</h3>
    <p>Some text will get selected and 
    then modified using the modify method.</p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
</body>
</html>

Output:

 

Example 2: This example will show the backward paragraph extension of the selection.




<!DOCTYPE html>
<html>
  
<head>
    <title>Web API</title>
</head>
  
<body>
    <script>
        function clickHandler() {
            let selection = window.getSelection();
            selection.modify('extend', 'backward', 'paragraph');
        }
    </script>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection modify method</h3>
    <p>Here is some garbage text just to show the 
        usage of the modify method.<br/>
        Some more text here. Some extra text. Some
        more text here. Some more text. Some more text.</p>
    <p>Here is some garbage text just to show the 
        usage of the modify method. Some more text here. 
        Some extra text. Some more text here.<br/>
        Some more text. Some more text.</p>
      
    <p>Here is some garbage text just to
        show the usage of the modify method.<br/>
        Some more text here.<br/>
        Some extra text. Some
        more text here. Some more text. 
        Some more text.</p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
</body>
</html>

Output:

 

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


Article Tags :