HTMLTextAreaElement: setRangeText() method - Web APIs | MDN

Syntax

js

setRangeText(replacement)
setRangeText(replacement, startSelection)
setRangeText(replacement, startSelection, endSelection)
setRangeText(replacement, startSelection, endSelection, selectMode)

Parameters

replacement

The string to insert.

selectionStart Optional

The index of the first selected character. An index greater than the length of the element's value is treated as pointing to the end of the value.

selectionEnd Optional

The index of the character after the last selected character. An index greater than the length of the element's value is treated as pointing to the end of the value. If selectionEnd is less than selectionStart, then both are treated as the value of selectionEnd.

selectMode Optional

A keyword, either select, start, end, or the default preserve, defining how the selection should be set after the text has been replaced.

Return value

None (undefined).

Examples

Click the button in this example to replace part of the text in the text box. The newly inserted text will be highlighted (selected) afterwards.

HTML

html

<label for="ta">Example text input:</label>
<textarea id="ta">
  This text has NOT been updated.
</textarea>
<button id="btn">Update text</button>

JavaScript

js

const btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  changeText();
});

function changeText() {
  const textarea = document.getElementById("ta");
  textarea.focus();
  textarea.setRangeText("ALREADY", 14, 17, "select");
}

Result

Specifications

Specification
HTML
# dom-textarea/input-setrangetext-dev

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.