document.getSelection() returns the document’s Selection object — the text the user highlighted, or the caret position when nothing is highlighted (MDN). It takes no parameters.
Pass the required arguments shown below. Check return values and browser support before you rely on the result.
Syntax
Call document.getSelection. Start with this line.
JavaScript
document.getSelection()
Call
What it does
document.getSelection()
Primary signature.
document.getSelection(...)
Call with the arguments your case needs.
Built into the browser. Call getSelection(...) on document — no import required.
Library declarations
JavaScript
document.getSelection()
Parameters
Parameter
Description
String form
Optional. selection.toString() for the highlighted text
Return Value
Return Value
Description
*
Selection, or null without a browsing context
JavaScript Examples
Example 1 — Read the Selection Object
Call getSelection() and inspect type, range count, and collapsed state.
Guard rangeCount. Avoid calling getRangeAt when there is no range.
Read index 0. MDN example uses the first range for common single selections.
Use the Range.toString() / collapsed describe that span.
Build ranges too. Pair with createRange() when you create selections yourself.
Compatibility
Browser Support
Document.getSelection() is Baseline Widely available on MDN (since November 2017). Logos use the shared browser-image-sprite.png sprite from this project.
✓ Baseline Widely available
Document.getSelection()
Selection object for selected text and caret across all major browsers.
BaselineWidely available
Google ChromeSupported
Yes
Mozilla FirefoxSupported
Yes
Apple SafariSupported
Yes
Microsoft EdgeSupported
Yes
OperaSupported
Yes
Internet ExplorerSupported (legacy)
Yes
getSelection()Wide
Bottom line: Safe for reading page selections. Remember input/textarea quirks in some browsers, and that selection is not the same as focus. See the MDN Document.getSelection() reference.
Frequently Asked Questions
MDN: Document.getSelection() returns the Selection object associated with this document, representing the range of text selected by the user, or the current position of the caret.
No. MDN marks Document.getSelection() as Baseline Widely available (since November 2017). It is not Deprecated, Experimental, or Non-standard.
A Selection object, or null if the document has no browsing context — for example, the document of an iframe that is not attached to a document (MDN).
Call selection.toString(). Some functions like alert() call toString() automatically, but not all do — MDN recommends calling toString() explicitly when you need a string.
Yes. Window.getSelection() returns the Selection for the window's document and is the common alias of document.getSelection().
No. MDN: notice the difference between selection and focus. Document.activeElement returns the focused element.