W3cubDocs

/DOM

window.getSelection

Returns a Selection object representing the range of text selected by the user or the current position of the caret.

Syntax

selection = window.getSelection();

Value

A Selection object.

When cast to string, either by appending an empty string ("") or using Selection.toString(), this object returns the text selected.

Example

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 a Selection object.
  • selectedText is a string (Selected text).

It's also useful to note that you can call Document.getSelection(), which works identically.

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.

Specifications

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) 9 (Yes) (Yes)
Feature Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 56 (Yes) 55 (No support for selection events) ? 37 5.1 (No support for selection start)

See also

© 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/window/getSelection