HTMLInputElement.setRangeText()
The HTMLInputElement.setRangeText()
method replaces a range of text in an <input>
or <textarea>
element with a new string.
Syntax
element.setRangeText(replacement); element.setRangeText(replacement, start, end [, selectMode]);
Parameters
replacement
-
The string to insert.
-
start
Optional -
The 0-based index of the first character to replace. Defaults to the current
selectionStart
value (the start of the user's current selection). -
end
Optional -
The 0-based index of the character after the last character to replace. Defaults to the current
selectionEnd
value (the end of the user's current selection). -
selectMode
Optional -
A string defining how the selection should be set after the text has been replaced. Possible values:
-
"select"
selects the newly inserted text. -
"start"
moves the selection to just before the inserted text. -
"end"
moves the selection to just after the inserted text. -
"preserve"
attempts to preserve the selection. This is the default.
-
Example
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
<input type="text" id="text-box" size="30" value="This text has NOT been updated."> <button onclick="selectText()">Update text</button>
JavaScript
function selectText() { const input = document.getElementById('text-box'); input.focus(); input.setRangeText('ALREADY', 14, 17, 'select'); }
Result
Specifications
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
setRangeText |
24 |
79 |
27 |
No |
15 |
7 |
≤37 |
25 |
27 |
14 |
7 |
1.5 |
See also
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText