<input type="text" id="text-box" size="20" value="Mozilla" />
<button>Select text</button>HTMLInputElement: setSelectionRange() method / notebook
HTMLInputElement: setSelectionRange() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.setSelectionRange(2, 5);
}
document.querySelector("button").addEventListener("click", selectText);<input type="text" id="caret-box" size="20" value="Mozilla" />
<label>
Position
<input type="number" id="caret-position" min="0" max="7" value="2" />
</label>
<button>Move caret</button>const input = document.getElementById("caret-box");
const position = document.getElementById("caret-position");
document.querySelector("button").addEventListener("click", () => {
const index = position.valueAsNumber;
input.focus();
input.setSelectionRange(index, index);
});