Window.getSelection()
The Window.getSelection()
method returns a Selection
object representing the range of text selected by the user or the current position of the caret.
Syntax
selection = window.getSelection();
Return value
A Selection
object.
When cast to string, either by appending an empty string (""
) or using Selection.toString()
, this object returns the text selected.
When called on an <iframe>
that is not displayed (eg. where display: none
is set) Firefox will return null
, whereas other browsers will return a Selection
object with Selection.type
set to None
.
Examples
function foo() { var selObj = window.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()
or document.write()
), 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 will result 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 aSelection
object. -
selectedText
is a string (Selected text).
Related objects
You can call Document.getSelection()
, which works identically to Window.getSelection()
.
It is worth noting that currently getSelection()
doesn't work on the content of <textarea>
and <input>
elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange()
or the selectionStart
and selectionEnd
properties could be used to work around this.
Notice also the difference between selection and focus. Document.activeElement
returns the focused element.
Specifications
Specification |
---|
Selection API # dom-window-getselection |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
getSelection |
1 |
12 |
1 |
9 |
9 |
1 |
1 |
18 |
4 |
10.1 |
1 |
1.0 |
See also
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection