DOM Methods

HTMLTextAreaElement.setSelectionRange()

Sets start and end offsets and direction in a multiline text control. A collapsed range represents a caret position. The selection state can be set without focus, but visible highlighting generally needs focus. Example result: Wel.

Formal Syntax & Structure

html syntaxhtml
element.setSelectionRange(start, end, direction)

Parameters & Attributes

NameTypeDescription
startnumberStart offset.
endnumberEnd offset, exclusive.
directionstringOptional selection direction.

Return Value

undefined

No return value.

Working Example

Example Snippethtml
<textarea id="demo">Welcome</textarea><p>Result: <output id="result"></output></p><script>const e = document.getElementById('demo');const result = value => { document.getElementById("result").textContent = String(value); };e.setSelectionRange(0,3); result(e.value.slice(e.selectionStart,e.selectionEnd));</script>
HTML Reference