setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
Parameters
selectionStart
-
The 0-based index of the first selected character. An index greater than the length of the element's value is treated as pointing to the end of the value.
selectionEnd
-
The 0-based index of the character after the last selected character. An index greater than the length of the element's value is treated as pointing to the end of the value. If
selectionEnd
is less thanselectionStart
, then both are treated as the value ofselectionEnd
. selectionDirection
Optional-
A string indicating the direction in which the selection is considered to have been performed. Possible values:
"forward"
"backward"
"none"
if the direction is unknown or irrelevant. Default value.
Return value
None (undefined
).
Exceptions
InvalidStateError
DOMException
-
Thrown if the element is not one of the following input types:
text
, orurl
.
Examples
Click the button in this example to select the third, fourth, and fifth characters in the text box ("zil" in the word "Mozilla").
HTML
<input type="text" id="text-box" size="20" value="Mozilla" />
<button onclick="selectText()">Select text</button>
JavaScript
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.setSelectionRange(2, 5);
}
Result
Specifications
Specification |
---|
HTML # dom-textarea/input-setselectionrange-dev |
Browser compatibility
BCD tables only load in the browser