MDN self-hosted library · e01.org

Window: getSelection() method

Selection API

Selection API

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

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

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

console.log(selection); // Selection object

Specifications

Browser compatibility

See also

  • Selection API
  • Selection
  • Range
  • Document.getSelection()
  • HTMLInputElement.setSelectionRange()