DOM Methods
HTMLInputElement.setSelectionRange()
Sets text selection offsets and optionally direction. Only text-like supported input types expose this method; number inputs can throw InvalidStateError. Offsets count UTF-16 code units, and visible highlighting depends on focus. Example result: ell.
Formal Syntax & Structure
html syntaxhtml
element.setSelectionRange(start, end, direction)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| start | number | Start offset. |
| end | number | End offset, exclusive. |
| direction | string | Optional forward, backward or none. |
Return Value
undefined
No return value.
Working Example
Example Snippethtml
<input id="demo" type="text" value="Hello"><p> Result: <output id="result"></output></p><script> const e = document.getElementById('demo'); const result = value => { document.getElementById("result").textContent = String(value); }; e.setSelectionRange(1,4); result(e.value.slice(e.selectionStart,e.selectionEnd));</script>