aboutsummaryrefslogtreecommitdiff
path: root/files/ja/web/api/document/getselection/index.html
blob: 5e416caf0bace1f8e997f521729c8a31d6a1d2d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
---
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>