<label for="text-box">Select some text:</label>
<input id="text-box" type="text" value="The quick brown fox." />
<button id="show-selection" type="button">Show selection</button>
<p id="output">No selection reported yet.</p>HTMLInputElement: selectionEnd property / notebook
HTMLInputElement: selectionEnd property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
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}).`;
});