HTMLInputElement: setSelectionRange() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheHTMLInputElement.setSelectionRange() method sets the start and end positions of the current text selection in an<input> or<textarea> element. This updates the selection state immediately, though the visual highlight only appears when the element is focused.
Optionally, you can specify the direction in which selection should be considered to have occurred. This lets you indicate, for example, that the selection was set by the user clicking and dragging from the end of the selected text toward the beginning.
This method updates theHTMLInputElement.selectionStart,HTMLInputElement.selectionEnd, andHTMLInputElement.selectionDirection properties in one call, regardless of whether the element is focused. The visual selection highlight will only appear when the element has focus.
The element must be of one of the following input types:password,search,tel,text, orurl. Otherwise the browser throws anInvalidStateError exception.
If you wish to selectall text of an input element, you can use theHTMLInputElement.select() method instead.
In this article
Syntax
setSelectionRange(selectionStart, selectionEnd)setSelectionRange(selectionStart, selectionEnd, selectionDirection)Parameters
selectionStartThe 0-based index of the first selected character. An index greater than the lengthof the element's value is treated as pointing to the end of the value.
selectionEndThe 0-based index of the characterafter the last selected character. Anindex greater than the length of the element's value is treated as pointing to the endof the value. If
selectionEndis less thanselectionStart, then both are treated as the value ofselectionEnd.selectionDirectionOptionalA string indicating the direction in which the selection is considered to have beenperformed. Possible values:
"forward""backward""none"if the direction is unknown or irrelevant. Default value.
Return value
None (undefined).
Exceptions
Examples
Click the button in this example to select the third, fourth, and fifth characters inthe text box ("zil" in the word "Mozilla").
HTML
<input type="text" size="20" value="Mozilla" /><button>Select text</button>JavaScript
function selectText() { const input = document.getElementById("text-box"); input.focus(); input.setSelectionRange(2, 5);}document.querySelector("button").addEventListener("click", selectText);Result
Specifications
| Specification |
|---|
| HTML> # dom-textarea/input-setselectionrange-dev> |