getSelection() method of
Document interface returns a
object representing the range of text selected by the user, or the current position of
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
automatically and the returned value is passed to the function. As a consequence, this will return the selected text
and not the
However, not all functions call
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
It is worth noting that currently
getSelection() doesn't work on the
<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.
|Selection API |
BCD tables only load in the browser