ブラウザ標準 DOM Selection API(window.getSelection())のクイックリファレンスガイドです。
🔗 関連ドキュメント: DOM Range API チートシート
現在の選択範囲の取得(Getting Current Selection)
const selection = window.getSelection(); // または document.getSelection()
const selectedText = selection.toString();
Range の管理(Range Management)
// アクティブな Range へのアクセス
const rangeCount = selection.rangeCount;
if (rangeCount > 0) {
const currentRange = selection.getRangeAt(0);
}
// すべてのアクティブな選択を解除(テキスト選択をクリア)
selection.removeAllRanges();
// プログラムから新しい選択範囲を設定
selection.addRange(range);
// 特定の Range を解除
selection.removeRange(range);
キャレットと折りたたみ(Caret & Collapsing)
// 選択を単一の点(キャレット)に折りたたむ
selection.collapse(parentNode, offset);
// 選択の先頭または末尾に折りたたむ
selection.collapseToStart();
selection.collapseToEnd();
// 選択範囲が現在折りたたまれているか確認(点滅カーソル状態)
const isCaret = selection.isCollapsed;
選択範囲の削除(Selection Deletion)
// 生のDOMドキュメントから選択されたコンテンツを削除
selection.deleteFromDocument();
選択変更イベント(Selection Change Events)
document.addEventListener('selectionchange', () => {
const sel = document.getSelection();
// 選択変更をログ出力
console.log('Selection changed:', sel.toString());
});