dom / latest / document / getselection.html /

Document.getSelection()

The getSelection() property of the Document interface returns a Selection object representing the range of text selected by the user, or the current position of the caret.

Syntax

getSelection()

Parameters

None.

Return value

A Selection object.

Examples

Getting a Selection object

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

console.log(selection); // Selection object

String representation of the Selection object

Some functions (like Window.alert()) call toString() automatically and the returned value is passed to the function. As a consequence, this will return the selected text and not the Selection object:

alert(selection);

However, not all functions call toString() automatically. To use a Selection object as a string, call its toString() method directly:

let selectedText = selection.toString();

You can call Window.getSelection(), which works identically to Document.getSelection().

It is worth noting that currently getSelection() doesn't work on the content of <input> elements in Firefox. HTMLInputElement.setSelectionRange()) could be used to work around this.

Notice also the difference between selection and focus. Document.activeElement returns the focused element.

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
getSelection
1
12
1
9
≤12.1
4
≤37
18
4
≤12.1
3.2
1.0

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getSelection