HTMLTextAreaElement: selectionStart property
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The selectionStart property of the HTMLTextAreaElement interface specifies the start position of the current text selection in a <textarea> element.
Value
A non-negative number.
Description
The selectionStart property is a number representing the zero-based index of the first selected character in a <textarea>. The property can be used to retrieve or set the start position.
When nothing is selected, the value of both selectionStart and selectionEnd is the position of the cursor (caret) inside the <textarea> element.
Setting selectionStart to a value greater than the current value of selectionEnd updates both properties to the new value. Values greater than the textLength are treated as textLength.
The property value can be retrieved and set without the <textarea> having focus, but the element must have focus for the ::selection pseudo-element to match the selected text.
Setting selectionStart to a new value fires the selectionchange and select events.
Examples
>Basic usage
This example reports the selected text and its start and end positions. Select some text in the textarea, and then click the button.
HTML
<label for="text-box">Select some text:</label>
<textarea id="text-box" rows="3">The quick brown fox.</textarea>
<button id="show-selection" type="button">Show selection</button>
<p id="output">No selection reported yet.</p>
JavaScript
const textBox = document.querySelector("#text-box");
const output = document.querySelector("#output");
document.querySelector("#show-selection").addEventListener("click", () => {
const start = textBox.selectionStart;
const end = textBox.selectionEnd;
const selectedText = textBox.value.substring(start, end);
output.textContent = `You selected "${selectedText}" (start: ${start}, end: ${end}).`;
});
Result
Specifications
| Specification |
|---|
| HTML> # dom-textarea/input-selectionstart> |
Browser compatibility
See also
<textarea>HTMLTextAreaElementHTMLTextAreaElement.selectionEndHTMLTextAreaElement.selectionDirectionHTMLTextAreaElement.textLengthselectionchangeeventHTMLTextAreaElement.select()HTMLTextAreaElement.setSelectionRange()HTMLTextAreaElement.setRangeText()HTMLInputElement.selectionStartSelection::selectionpseudo-element