HTMLTextAreaElement: setSelectionRange() method - Web APIs | MDN
Syntax
js
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
Parameters
selectionStart-
The 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. See the
selectionStartproperty for more information. selectionEnd-
The 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
selectionEndis less thanselectionStart, then both are treated as the value ofselectionEnd. See theselectionEndproperty for more information. selectionDirectionOptional-
The keyword
"forward","backward", or the default"none"— indicating the direction in which the selection is considered to have been performed. See theselectionDirectionproperty for more information.
Return value
None (undefined).
Examples
js
const textarea = document.getElementById("text-box");
const chars = textarea.textLength;
// if the value is more than 10 characters long
if (chars > 10) {
// Element must be focused to select a range of text within it
textarea.focus();
// select the text between the fifth character from the start and
// the fifth character from the end
textarea.setSelectionRange(5, chars - 5);
} else {
// otherwise select all the text
textarea.select();
}
Specifications
| Specification |
|---|
| HTML # dom-textarea/input-setselectionrange-dev |