The HTMLInputElement.setSelectionRange() method sets the start and end positions of the current text selection in an <input> element.

Optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred; this lets you indicate, for example, that the selection as set by the user clicking and dragging from the end of the selected text toward the beginning.

This method updates HTMLInputElement.selectionStart, selectionEnd, and selectionDirection in one call.


inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);


The index of the first selected character.
The index of the character after the last selected character.
selectionDirection Optional
A string indicating the direction in which the selection was performed. This may be "forward" or "backward", or "none" if the direction is unknown or irrelevant.


The following code:

<!DOCTYPE html>
<meta charset=utf-8 />
<title>JS Bin</title>
function SelectText () {     
        var input = document.getElementById("mytextbox");
  <p><input type="text" id="mytextbox" size="20" value="Mozilla"/></p>
  <p><button onclick="SelectText()">Select text</button></p>

will produce the following:


Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1.0 1.0 (1.7 or earlier) 9 8.00 At least 3
selectionDirection 15 8.0 (8.0) ? ? (Yes)
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?
selectionDirection ? 8.0 (8.0) ? ? ?

The support for selectionDirection was added to Gecko in bug 674558, and to Blink/Webkit in WebKit bug 60403. See also

See also

Document Tags and Contributors

Last updated by: Nickolay,
Hide Sidebar