Selection API

Working with text selection, ranges, and the Selection API in contenteditable elements.

Getting the selection

The window.getSelection() method returns a Selection object representing the current text selection.

const selection = window.getSelection();

if (selection && selection.rangeCount > 0) {
  const range = selection.getRangeAt(0);
  console.log('Selected text:', range.toString());
  console.log('Start:', range.startOffset);
  console.log('End:', range.endOffset);
}

Range API

A Range represents a contiguous portion of the document. You can create, modify, and manipulate ranges programmatically.

// Create a new range
const range = document.createRange();

// Set the range to cover specific content
range.setStart(element.firstChild, 5);
range.setEnd(element.firstChild, 10);

// Apply the range to the selection
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

Common issues

Selection lost on focus change

When a contenteditable loses focus, window.getSelection() may return null or an empty selection, making it difficult to preserve selection state.

See cases: scenario-selection-api-behavior

Incorrect range boundaries

When selecting text that spans multiple elements, the Range boundaries may not accurately reflect the visual selection, especially across element boundaries.

See cases: scenario-selection-range-accuracy

Selection collapse on blur

Clicking outside a contenteditable may collapse the selection unexpectedly, even when the click target is within the same document.

See cases: scenario-selection-collapse-on-blur

Related resources