--- title: Document.getSelection() slug: Web/API/Document/getSelection tags: - API - Document - Method - Reference - getSelection browser-compat: api.Document.getSelection translation_of: Web/API/Document/getSelection original_slug: Web/API/DocumentOrShadowRoot/getSelection --- <div>{{APIRef("DOM")}}</div> <p><span class="seoSummary"><strong><code>getSelection()</code></strong> は {{DOMxRef("Document")}} インターフェイスのプロパティで、ユーザーが選択したテキストの範囲、またはキャレットの現在位置を表す {{DOMxRef("Selection")}} オブジェクトを返します。</span></p> <h2 id="Syntax">構文</h2> <pre class="brush: js">getSelection()</pre> <h3 id="Parameters">引数</h3> <p>なし。</p> <h3 id="Returns">返値</h3> <p>{{DOMxRef("Selection")}} オブジェクト。</p> <h2 id="Example">例</h2> <h3 id="Getting_a_Selection_object">Selection オブジェクトを取得</h3> <pre class="brush:js"> let selection = document.getSelection(); let selRange = selection.getRangeAt(0); // この範囲に対して何かをする console.log(selection); // Selection オブジェクト </pre> <h3 id="String_representation_of_the_Selection_object">Selection オブジェクトの文字列表現</h3> <p>JavaScript では、オブジェクトが文字列を取る関数 ({{DOMxRef("Window.alert()")}} など) に渡された場合、オブジェクトの {{JSxRef("Object.toString", "toString()")}} メソッドが呼び出され、関数にその返値が渡されます。これにより、プロパティやメソッドを持つ実際のオブジェクトであった場合、他の関数に使われると文字列になって現れることがあります。</p> <pre class="brush:js;">alert(selection);</pre> <p>ただし、すべての関数で自動的に <code>toString()</code> が呼び出されるとは限りません。 <code>Selection</code> オブジェクトを文字列として使用する場合は、 <code>toString()</code> メソッドを直接呼び出してください。</p> <pre class="brush:js;">let selectedText = selection.toString();</pre> <h2 id="Related_objects">関連するオブジェクト</h2> <p>{{domxref("Window.getSelection()")}} を呼び出すと、 <code>Document.getSelection()</code> と同等の動作をします。</p> <p>Firefox において現在は <code>getSelection()</code> は {{htmlelement("input")}} 要素の中では動作しないことに注意してください。 {{domxref("HTMLInputElement.setSelectionRange()")}} を使用することで回避できます。</p> <p><em>selection</em> と <em>focus</em> との違いにも注意してください。 {{domxref("Document.activeElement")}} はフォーカスを持つ要素を返します。</p> <h2 id="Specifications">仕様書</h2> {{Specifications}} <h2 id="Browser_compatibility">ブラウザーの互換性</h2> <p>{{Compat}}</p>