MDN wants to talk to developers like you: https://qsurvey.mozilla.com/s3/8d22564490d8

Window.getSelection()

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

요약

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

문법

selection = window.getSelection();
  • selection은 Selection객체입니다. 빈 문자열("") 을 추가(+"")  하거나 String.toString()을 호출하면 객체가 선택된 text를 반환합니다.

예제

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

노트

Selection 객체의 문자열 표현

In JavaScript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods.

In JavaScript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods.

In the above example, selObj.toString() is automatically called when it is passed to window.alert(). However, attempting to use a JavaScript String property or method such as length or substr directly on a Selection object will result in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its toString() method directly:

var selectedText = selObj.toString();
  • selObj is a Selection object.
  • selectedText is a string (Selected text).

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.

Specifications

Specification Status Comment
HTML Editing APIs
The definition of 'Window.getSelection()' in that specification.
Editor's Draft Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 9 (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?

See also

문서 태그 및 공헌자

 이 페이지의 공헌자: WonbaeLee
 최종 변경: WonbaeLee,