Window: getSelection() method

Baseline
Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

The getSelection() method of the Window interface returns the Selection object associated with the window's document, representing the range of text selected by the user, or the current position of the caret.

window.getSelection() is a shorthand for window.document.getSelection(). Read Document.getSelection() for more information.

Syntax

js
getSelection()

Parameters

None.

Return value

A Selection object, or null if the associated document has no browsing 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., where display: none is set) Firefox returns null, whereas other browsers returns a Selection object with Selection.type set to None.

Examples

Getting a Selection object

js
const selection = window.getSelection();
const selRange = selection.getRangeAt(0);
// do stuff with the range

console.log(selection); // Selection object

Specifications

Specification
Selection API
# dom-window-getselection

Browser compatibility

See also