DOM Methods

HTMLInputElement.setSelectionRange()

Build a form with the HTML form generator

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

NameTypeDescription
startnumberStart offset.
endnumberEnd offset, exclusive.
directionstringOptional 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>
HTML Reference