This is an experimental technology
Check 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.
var selection = documentOrShadowRootInstance.getSelection()
None.
A Selection
object.
function foo() { var selObj = document.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range }
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();
selObj
is a Selection
object.selectedText
is a string (Selected text).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.
Specification | Status | Comment |
---|---|---|
Shadow DOM The definition of 'DocumentOrShadowRoot' in that specification. | Obsolete | Initial definition. |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 53 | Yes | Yes | Yes | 40 | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | 53 | 53 | Yes | Yes | 40 | Yes | 6.0 |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/getSelection