Summary
Returns a selection object representing the range of text selected by the user.
Syntax
selection = window.getSelection() ;
selection
is a {{domxref("Selection")}} object. When cast to string, either by appending an empty string (""
) or using {{jsxref("String.toString()")}}, this object is the text selected.
Example
function foo() { var selObj = window.getSelection(); alert(selObj); var selRange = selObj.getRangeAt(0); // do stuff with the range }
Notes
In JavaScript, when an object is passed to a function expecting a string (like {{ Domxref("window.alert()") }} or {{ Domxref("document.write()") }}), the object's {{jsxref("Object.toString", "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 {{domxref("window.alert()")}}. However, attempting to use a JavaScript String property or method such as length
or substr
directly on a {{domxref("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).
It's also useful to note that you can call {{domxref("Document.getSelection()")}}, which works identically.
Browser compatibility
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | Yes | Yes | From version 9 | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | {{ CompatUnknown() }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} |
Specification
See also
- {{domxref("Selection")}}
- {{domxref("Range")}}
- {{domxref("Document.getSelection()")}}