0%

Selection과 Range를 이용하여 유연하게 노드 조작하기

텍스트의 범위를 드래그/ 선택함에 따라 생기는 Range와 이를 가능하게 하는 Selection 객체를 이용해 커서 혹은 블록의 위치를 특정할 수 있다.

이 과정 없이 focus 를 취하면 커서의 위치는 텍스트의 처음으로 설정된다.

  • element의 타입은 HTMLElement이다.
  • Selection은 Node 조작이 가능한 범위를 지정해주는 window (global) 메소드 이용
  • Range는 개별 Node를 생성하는 것이므로 document 메소드 이용

document는 window의 프로퍼티 (window.document는 document에 대한 레퍼런스를 리턴한다) 이다.

1
2
// Fragment of a document that can contain nodes and parts of text nodes
const range = document.createRange();
1
2
// Selection object representing the range of text selected by the user or the current position of the caret
const selection = window.getSelection();
1
2
// sets the Range to the contents of a Node
range.selectNodeContents(element);
1
2
3
4
// collapse the Range to one of its boundary points
// collapsed Range: empty, containing no content, specifying a single-point in a DOM tree
// toStart === false: collapses the Range to its end
range.collapse(false);
1
2
3
4
// set the anchorNode & focusNode to null
selection?.removeAllRanges();
selection?.addRange(range);
element.focus();