Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Document
  4. getSelection()

Document: 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 November 2017.

ThegetSelection() method of theDocument interface returns theSelection object associated with this document, representing the range of text selected by the user, or the current position of the caret.

Syntax

js
getSelection()

Parameters

None.

Return value

ASelection object, ornull if the document has nobrowsing context (for example, it is the document of an<iframe> that is not attached to a document).

Examples

Getting a Selection object

js
const selection = document.getSelection();const selRange = selection.getRangeAt(0);// do stuff with the rangeconsole.log(selection); // Selection object

String representation of the Selection object

Some functions (likeWindow.alert()) calltoString()automatically and the returned value is passed to the function. As a consequence, this will return the selected textand not theSelection object:

js
alert(selection);

However, not all functions calltoString() automatically.To use aSelection object as a string, call itstoString() method directly:

js
let selectedText = selection.toString();

Related objects

You can callWindow.getSelection(), which is identical towindow.document.getSelection().

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

Notice also the difference betweenselection andfocus.Document.activeElement returns the focused element.

Specifications

Specification
Selection API
# dom-document-getselection

Browser compatibility

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp