Window.getSelection()

요약

사용자 또는 Caret의 위치에 따라 선택된 텍스트의 범위를 나타내는 Selection (en-US) 객체를 반환한다.

문법

js
selection = window.getSelection();

예제

js
function foo() {
  var selObj = window.getSelection();
  alert(selObj);
  var selRange = selObj.getRangeAt(0);
  // do stuff with the range
}

노트

Selection 객체의 문자열 표현

JavaScript에서 문자열을 인자로 받는 함수(window.alert()document.write() (en-US) 같은)에 객체를 전달하면 해당 객체의 toString() 메소드를 호출하고 그 결과를 호출한 함수로 전달합니다. 이를 통해서 실제로는 속성과 메소드를 갖는 문자열이 아닌 일반적인 객체라 하더라도 문자열을 인자로 받는 함수의 인자로 사용할 때에는 객체를 문자열인 것처럼 전달할 수 있습니다.

위 예제에서 selObj를 window.alert()의 인자로 전달하면 selObj.toString()가 자동적으로 호출됩니다. 하지만, selObj에 대해서 lengthsubstr 같은 JavaScript String의 속성이나 메소드를 사용하면 객체에 그러한 속성이나 메소드가 없기 때문에 에러나 예상치 못한 결과가 발생합니다. Selection 객체를 문자열로 사용하려면 다음처럼 직접 toString() 메소드를 호출해야 합니다:

js
var selectedText = selObj.toString();
  • selObjSelection 객체입니다.
  • selectedText는 문자열 (선택한 문자열)입니다.

It's also useful to note that you can call Document.getSelection(), which works identically.

HTML inputs provide simpler helper APIs for working with selection (see HTMLInputElement.setSelectionRange()).

Notice the difference between selection and focus. Document.activeElement returns the focused element.

명세서

Specification
Selection API
# dom-window-getselection

브라우저 호환성

BCD tables only load in the browser

See also