Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015년 7월.
사용자 또는 Caret의 위치에 따라 선택된 텍스트의 범위를 나타내는 Selection 객체를 반환한다.
JavaScript에서 문자열을 인자로 받는 함수(window.alert() 나 document.write() 같은)에 객체를 전달하면 해당 객체의 toString() 메소드를 호출하고 그 결과를 호출한 함수로 전달합니다. 이를 통해서 실제로는 속성과 메소드를 갖는 문자열이 아닌 일반적인 객체라 하더라도 문자열을 인자로 받는 함수의 인자로 사용할 때에는 객체를 문자열인 것처럼 전달할 수 있습니다.
위 예제에서 selObj를 window.alert()의 인자로 전달하면 selObj.toString()가 자동적으로 호출됩니다. 하지만, selObj에 대해서 length 나 substr 같은 JavaScript String의 속성이나 메소드를 사용하면 객체에 그러한 속성이나 메소드가 없기 때문에 에러나 예상치 못한 결과가 발생합니다. Selection 객체를 문자열로 사용하려면 다음처럼 직접 toString() 메소드를 호출해야 합니다:
var selectedText = selObj.toString();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.
| Selection API # dom-window-getselection |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2023년 7월 30일 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.