files/en-us/web/api/htmlinputelement/setselectionrange/index.md
{{APIRef("HTML DOM")}}
The HTMLInputElement.setSelectionRange() method sets the start and end positions of the current text selection in an {{HTMLElement("input")}} or {{HTMLElement("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 the {{domxref("HTMLInputElement.selectionStart")}}, {{domxref("HTMLInputElement.selectionEnd")}}, and {{domxref("HTMLInputElement.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, or url. Otherwise the browser throws an InvalidStateError exception.
If you wish to select all text of an input element, you can use the HTMLInputElement.select() method instead.
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
selectionStart
selectionEnd
selectionEnd is less than selectionStart, then both are treated as the value of selectionEnd.selectionDirection {{optional_inline}}
"forward""backward""none" if the direction is unknown or irrelevant. Default value.None ({{jsxref("undefined")}}).
InvalidStateError {{domxref("DOMException")}}
Click the button in this example to select the third, fourth, and fifth characters in the text box ("zil" in the word "Mozilla").
<input type="text" id="text-box" size="20" value="Mozilla" />
<button>Select text</button>
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.setSelectionRange(2, 5);
}
document.querySelector("button").addEventListener("click", selectText);
{{EmbedLiveSample("Examples")}}
{{Specifications}}
{{Compat}}