This feature is well established and works across many devices and browser versions. It’s been available across browsers since November 2017.
The getSelection() method of the Document interface returns the Selection object associated with this document, representing the range of text selected by the user, or the current position of the caret.
getSelection()
None.
A Selection object, or null if the document has no browsing context (for example, it is the document of an <iframe> that is not attached to a document).
const selection = document.getSelection(); const selRange = selection.getRangeAt(0); // do stuff with the range console.log(selection); // Selection object
Some functions (like Window.alert()) call toString() automatically and the returned value is passed to the function. As a consequence, this will return the selected text and not the Selection object:
alert(selection);
However, not all functions call toString() automatically. To use a Selection object as a string, call its toString() method directly:
let selectedText = selection.toString();
You can call Window.getSelection(), which is identical to window.document.getSelection().
It is worth noting that currently getSelection() doesn't work on the content of <input> elements in Firefox. HTMLInputElement.setSelectionRange()) could be used to work around this.
Notice also the difference between selection and focus. Document.activeElement returns the focused element.
| Specification |
|---|
| Selection API> # dom-document-getselection> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
getSelection |
2 | 12 | 57 | ≤12.1 | 4 | 18 | 57 | ≤12.1 | 3.2 | 1.0 | 4.4 | 3.2 |
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getSelection