This is an experimental technologyCheck the Browser compatibility table carefully before using this in production.
The getSelection() property of the DocumentOrShadowRoot interface returns a Selection object representing the range of text selected by the user, or the current position of the caret.
Syntax
var selection = documentOrShadowRootInstance.getSelection()
Parameters
None.
Returns
A Selection object.
Example
function foo() {
var selObj = document.getSelection();
alert(selObj);
var selRange = selObj.getRangeAt(0);
// do stuff with the range
}
Notes
String representation of the Selection object
In JavaScript, when an object is passed to a function expecting a string (like Window.alert()), 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 results 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();
selObjis aSelectionobject.selectedTextis a string (Selected text).
Related objects
You can call Window.getSelection(), which works identically to 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.
Specifications
| Specification | Status | Comment |
| Shadow DOMThe definition of 'DocumentOrShadowRoot' in that specification. | Obsolete | Initial definition. |
Browser Compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Chrome
Full support 53 |
Edge
Full support 12 |
Firefox
Full support 63 |
IE
Full support Yes |
Opera
Full support 40 |
Safari
Full support Yes |
WebView Android
Full support 53 |
Chrome Android
Full support 53 |
Firefox Android
Full support 63 |
Opera Android
Full support 41 |
Safari iOS
Full support Yes |
Samsung Internet Android
Full support 6.0 |
Legend
- Full support
- Full support
- Experimental. Expect behavior to change in the future.'
- Experimental. Expect behavior to change in the future.
DocumentOrShadowRoot.getSelection() by Mozilla Contributors is licensed under CC-BY-SA 2.5.