This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

DOM Selection API Cheat Sheet

A quick reference guide for the browser DOM Selection API (document.getSelection): range manipulation, caret collapsing, and selection events.

· Published

A quick reference guide to the browser DOM Selection API (window.getSelection()).

🔗 Related: DOM Range API Cheat Sheet

Getting Current Selection

const selection = window.getSelection(); // or document.getSelection()
const selectedText = selection.toString();

Range Management

// Access the active range
const rangeCount = selection.rangeCount;
if (rangeCount > 0) {
  const currentRange = selection.getRangeAt(0);
}

// Clear all active selections (deselects all text)
selection.removeAllRanges();

// Set new selection programmatically
selection.addRange(range);

// Remove a specific range
selection.removeRange(range);

Caret & Collapsing

// Collapse selection to a single point (caret)
selection.collapse(parentNode, offset);

// Collapse to start or end boundary
selection.collapseToStart();
selection.collapseToEnd();

// Check if selection is currently collapsed (a blinking cursor)
const isCaret = selection.isCollapsed;

Selection Deletion

// Removes selected content from the live document DOM
selection.deleteFromDocument();

Selection Change Events

document.addEventListener('selectionchange', () => {
  const sel = document.getSelection();
  console.log('Selection changed:', sel.toString());
});

Related topics