Snabbreferens foer webblasarens DOM Selection API (window.getSelection()).
🔗 Relaterat: DOM Range API Lathund
Hämta aktuell markering (Getting Current Selection)
const selection = window.getSelection(); // eller document.getSelection()
const selectedText = selection.toString();
Intervallhantering (Range Management)
// Atkomst till aktivt intervall
const rangeCount = selection.rangeCount;
if (rangeCount > 0) {
const currentRange = selection.getRangeAt(0);
}
// Rensa alla aktiva markeringar (avmarkerar all text)
selection.removeAllRanges();
// Satt ny markering programmatiskt
selection.addRange(range);
// Ta bort ett specifikt intervall
selection.removeRange(range);
Markör och kollaps (Caret & Collapsing)
// Fall ihop markering till en enda punkt (markor)
selection.collapse(parentNode, offset);
// Fall ihop till start- eller slutgrans
selection.collapseToStart();
selection.collapseToEnd();
// Kontrollera om markeringen ar hopfalld (blinkande markor)
const isCaret = selection.isCollapsed;
Borttagning av markering (Selection Deletion)
// Tar bort markerat innehall direkt fran levande DOM-dokument
selection.deleteFromDocument();
Händelser vid markeringsändring (Selection Change Events)
document.addEventListener('selectionchange', () => {
const sel = document.getSelection();
// Logga andring
console.log('Selection changed:', sel.toString());
});