From 362ba6775c2337ed3dc91d5320f7e891c3c74f99 Mon Sep 17 00:00:00 2001 From: MDN Date: Sat, 13 Mar 2021 00:26:44 +0000 Subject: [CRON] sync translated content --- files/ja/web/api/document/getselection/index.html | 88 +++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 files/ja/web/api/document/getselection/index.html (limited to 'files/ja/web/api/document/getselection') diff --git a/files/ja/web/api/document/getselection/index.html b/files/ja/web/api/document/getselection/index.html new file mode 100644 index 0000000000..81fc970c85 --- /dev/null +++ b/files/ja/web/api/document/getselection/index.html @@ -0,0 +1,88 @@ +--- +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 +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

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
+}
+ +

メモ

+ +

Selection オブジェクトの文字列表現

+ +

JavaScript では、オブジェクトが string を取る関数 ({{DOMxRef("Window.alert()")}} など) に渡された場合、オブジェクトの {{JSxRef("Object.toString", "toString()")}} メソッドが呼び出され、関数にその返値が渡されます。これにより、プロパティやメソッドを持つ実際のオブジェクトであった場合、他の関数に使われると文字列になって現れることがあります。

+ +

上記の例では、 selObj.toString() が呼び出されてから {{DOMxRef("Window.alert()")}} に渡されます。しかし、 JavaScript の String のプロパティやメソッド、例えば lengthsubstr が {{DOMxRef("Selection")}} オブジェクトに対して呼び出されると、そのプロパティやメソッドを持っていないため、エラーが発生するか予期しない結果が返ることがあります。 Selection オブジェクトを文字列として扱うには、 toString() メソッドを直接呼び出してください。

+ +
var selectedText = selObj.toString();
+ + + + + +

{{domxref("Window.getSelection()")}} を呼び出すと、 Document.getSelection() と同等の動作をします。

+ +

Firefox において現在は getSelection() は {{htmlelement("input")}} 要素の中では動作しないことに注意してください。 {{domxref("HTMLInputElement.setSelectionRange()")}}) を使用することで回避できます。

+ +

selectionfocus との違いにも注意してください。 {{domxref("Document.activeElement")}} はフォーカスを持つ要素を返します。

+ +

仕様書

+ + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName("Shadow DOM", "#extensions-to-the-documentorshadowroot-mixin", "DocumentOrShadowRoot")}}{{Spec2("Shadow DOM")}}初回定義
+ +

ブラウザーの互換性

+ +
+ + +

{{Compat("api.DocumentOrShadowRoot.getSelection")}}

+
-- cgit v1.2.3-54-g00ecf