빠른 참조

DOM Selection API 치트시트

브라우저 표준 DOM Selection API(document.getSelection) 빠른 참조: 범위 관리, 캐럿 축소(collapse), 선택 변경 이벤트.

· 게시일

브라우저 표준 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);

// 특정 범위 제거
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());
});

관련 주제