Document: getSelection() メソッド
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
構文
getSelection()
引数
なし。
返値
Selection
オブジェクト。
例
Selection オブジェクトを取得
let selection = document.getSelection();
let selRange = selection.getRangeAt(0);
// この範囲に対して何かをする
console.log(selection); // Selection オブジェクト
Selection オブジェクトの文字列表現
JavaScript では、オブジェクトが文字列を取る関数 (Window.alert()
など) に渡された場合、オブジェクトの toString()
メソッドが呼び出され、関数にその返値が渡されます。これにより、プロパティやメソッドを持つ実際のオブジェクトであった場合、他の関数に使われると文字列になって現れることがあります。
alert(selection);
ただし、すべての関数で自動的に toString()
が呼び出されるとは限りません。 Selection
オブジェクトを文字列として使用する場合は、 toString()
メソッドを直接呼び出してください。
let selectedText = selection.toString();
関連するオブジェクト
Window.getSelection()
を呼び出すと、 Document.getSelection()
と同等の動作をします。
Firefox において現在は getSelection()
は <input>
要素の中では動作しないことに注意してください。 HTMLInputElement.setSelectionRange()
を使用することで回避できます。
selection と focus との違いにも注意してください。 Document.activeElement
はフォーカスを持つ要素を返します。
仕様書
Specification |
---|
Selection API # dom-document-getselection |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
getSelection |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- Partial support
- Partial support
- Has more compatibility info.