Document: getSelection() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since November 2017.
ThegetSelection() method of theDocument interface returns theSelection object associated with this document, representing the range of text selected by the user, or the current position of the caret.
In this article
Syntax
getSelection()Parameters
None.
Return value
ASelection object, ornull if the document has nobrowsing context (for example, it is the document of an<iframe> that is not attached to a document).
Examples
>Getting a Selection object
const selection = document.getSelection();const selRange = selection.getRangeAt(0);// do stuff with the rangeconsole.log(selection); // Selection objectString representation of the Selection object
Some functions (likeWindow.alert()) calltoString()automatically and the returned value is passed to the function. As a consequence, this will return the selected textand not theSelection object:
alert(selection);However, not all functions calltoString() automatically.To use aSelection object as a string, call itstoString() method directly:
let selectedText = selection.toString();Related objects
You can callWindow.getSelection(), which is identical towindow.document.getSelection().
It is worth noting that currentlygetSelection() doesn't work on thecontent of<input> elements in Firefox.HTMLInputElement.setSelectionRange()) could be used to work around this.
Notice also the difference betweenselection andfocus.Document.activeElement returns the focused element.
Specifications
| Specification |
|---|
| Selection API> # dom-document-getselection> |