--- title: DocumentOrShadowRoot.getSelection() slug: Web/API/Document/getSelection tags: - API - DocumentOrShadowRoot - Doument - Method - Reference - ShadowRoot - getSelection - getSelection() - shadow dom translation_of: Web/API/DocumentOrShadowRoot/getSelection original_slug: Web/API/DocumentOrShadowRoot/getSelection ---
getSelection() は {{DOMxRef("DocumentOrShadowRoot")}} インターフェイスのプロパティで、ユーザーが選択したテキストの範囲、またはキャレットの現在位置を表す {{DOMxRef("Selection")}} オブジェクトを返します。
var selection = documentOrShadowRootInstance.getSelection()
なし。
{{DOMxRef("Selection")}} オブジェクト。
function foo() {
var selObj = document.getSelection();
alert(selObj);
var selRange = selObj.getRangeAt(0);
// do stuff with the range
}
JavaScript では、オブジェクトが string を取る関数 ({{DOMxRef("Window.alert()")}} など) に渡された場合、オブジェクトの {{JSxRef("Object.toString", "toString()")}} メソッドが呼び出され、関数にその返値が渡されます。これにより、プロパティやメソッドを持つ実際のオブジェクトであった場合、他の関数に使われると文字列になって現れることがあります。
上記の例では、 selObj.toString() が呼び出されてから {{DOMxRef("Window.alert()")}} に渡されます。しかし、 JavaScript の String のプロパティやメソッド、例えば length や substr が {{DOMxRef("Selection")}} オブジェクトに対して呼び出されると、そのプロパティやメソッドを持っていないため、エラーが発生するか予期しない結果が返ることがあります。 Selection オブジェクトを文字列として扱うには、 toString() メソッドを直接呼び出してください。
var selectedText = selObj.toString();
selObj は Selection オブジェクトです。selectedText は文字列 (選択中のテキスト) です。{{domxref("Window.getSelection()")}} を呼び出すと、 Document.getSelection() と同等の動作をします。
Firefox において現在は getSelection() は {{htmlelement("input")}} 要素の中では動作しないことに注意してください。 {{domxref("HTMLInputElement.setSelectionRange()")}}) を使用することで回避できます。
selection と focus との違いにも注意してください。 {{domxref("Document.activeElement")}} はフォーカスを持つ要素を返します。
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{SpecName("Shadow DOM", "#extensions-to-the-documentorshadowroot-mixin", "DocumentOrShadowRoot")}} | {{Spec2("Shadow DOM")}} | 初回定義 |
{{Compat("api.DocumentOrShadowRoot.getSelection")}}