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());
});