HTML | InputElement.setSelectionRange() method

The InputElement.setSelectionRange() method is used to set the start and end positions of the current index value to select text in an input or textarea element.

Syntax:

element.setSelectionRange( Start, End, Direction );

Parameters: This function accepts three parameters as mentioned above and described below:



  • Start: This parameter holds the index of the first selected character. The index value greater than the length of the element pointing to the end value.
  • End: This parameter holds the index of the character after the last selected character. The index value greater than the length of the element pointing to the end value.
  • Direction: This parameter holds the direction to perform selection operation. The possible value of direction are: forward, backward and None.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
  
<head
    <title>
        HTML | InputElement.setSelectionRange() method
    </title
</head
  
<body style="text-align:center;"
      
    <h1 style="color:green;"
        GeeksforGeeks 
    </h1
              
    <h2>
        HTML InputElement.setSelectionRange() method
    </h2
          
    <input type="text" id="geeks" size="50"
        value="Welcome to GeeksforGeeks">
      
    <button onclick="myGeeks()">
        Select text content
    </button
              
    <script
        function myGeeks() {
            const input = document.getElementById('geeks'); 
            input.focus();
            input.setSelectionRange(11, 24);
        }
    </script
</body>
  
</html>

chevron_right


Output:
Before Clicking the Button:

After Clicking the Button:

Supported Browsers: The browser supported by HTML InputElement.setSelectionRange() method are listed below:

  • Google Chrome 1.0
  • Internet Explorer 9.0
  • Firefox 1.0
  • Safari
  • Opera 8.0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.