Selection APIs Read Selected Text

selectionStart and selectionEnd expose the highlighted span inside an input, while getSelection with a Range reads text selected anywhere on the page.

JavascriptForm Validation

Code

javascriptsnippet
27 lines
// Two selection surfaces: text inside an input, text anywhere in the page.
const comment = document.createElement('textarea');
comment.value = 'The rate limit reset at noon';

// selectionStart / selectionEnd mark the highlighted span inside the input.
function inputSelection() {
  const { selectionStart, selectionEnd } = comment;
  if (selectionStart === selectionEnd) return null; // caret, not a range
  return comment.value.slice(selectionStart, selectionEnd);
}

comment.setSelectionRange(4, 14);
console.log('input selection:', inputSelection());

// Page-level selection works on non-editable content through a Range.
const article = document.createElement('article');
article.textContent = 'Deploy notes for the auth service';
const range = document.createRange();
range.selectNodeContents(article);
const selection = getSelection();
selection.removeAllRanges();
selection.addRange(range);
console.log('page selection:', selection.toString());

// Park the caret at the end so the next keystroke appends.
comment.setSelectionRange(comment.value.length, comment.value.length);
console.log('caret at end:', comment.selectionStart === comment.value.length);

What the code does

All of the logic lives in the function inputSelection.

What to watch for

  • The package manager never enters the picture for this snippet.
  • A browser is the runtime here: document are not available in Node.
  • The guard selectionStart === selectionEnd short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is function inputSelection()

Each run prints the 3 labeled blocks input selection:, page selection:, caret at end: in source order.

Statements that matter

if (selectionStart === selectionEnd) return null; // caret, not a range
return comment.value.slice(selectionStart, selectionEnd);

Interactive Tools for This Topic

FAQ

Does Selection APIs Read Selected Text run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.