Window: getSelection() method
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
ThegetSelection()
method of theWindow
interface returns theSelection
object associated with the window'sdocument
, representing the range of text selected by the user or the current position of the caret.
Syntax
getSelection()
Parameters
None.
Return value
ASelection
object, ornull
if the associated document has nobrowsing context (for example, the window is an<iframe>
that is not attached to a document).
When called on an<iframe>
that is not displayed (e.g., wheredisplay: none
is set) Firefox returnsnull
, whereas other browsers returns aSelection
object withSelection.type
set toNone
.
Examples
function foo() { const selObj = window.getSelection(); alert(selObj); const 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 (likewindow.alert()
ordocument.write()
), the object'stoString()
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 ispassed towindow.alert()
. However, attempting to use a JavaScriptString propertyor method such aslength
orsubstr
directly on aSelection
object will result in an error if it does nothave that property or method and may return unexpected results if it does. To use aSelection
object as a string, call itstoString()
methoddirectly:
const selectedText = selObj.toString();
selObj
is aSelection
object.selectedText
is a string (Selected text).
Related objects
You can callDocument.getSelection()
, which works identically toWindow.getSelection()
.
It is worth noting that currentlygetSelection()
doesn't work on thecontent of<textarea>
and<input>
elements in Firefoxand Edge (Legacy).HTMLInputElement.setSelectionRange()
or theselectionStart
andselectionEnd
properties could beused to work around this.
Notice also the difference betweenselection andfocus.Document.activeElement
returns the focused element.
Specifications
Specification |
---|
Selection API # dom-window-getselection |