Range: selectNodeContents() メソッド

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.

Range.selectNodeContents() メソッドは RangeNode のコンテンツを含むように設定します。

Range の開始と終わりの親ノード (Node) が参照ノードになります。 startOffset は 0 で、 endOffset は子 Node の数、または参照ノードに格納する文字数です。

構文

js
selectNodeContents(referenceNode)

引数

referenceNode

Range 内でコンテンツが選択されるノード (Node) です。

返値

なし (undefined)。

js
const range = document.createRange();
const referenceNode = document.querySelector("div");
range.selectNodeContents(referenceNode);

ライブ例

この例では、ユーザーがボタンで段落を選択・解除できるようにしています。 Document.createRange()Range.selectNodeContents()Selection.addRange() を使用してコンテンツを選択しています。 選択解除には Window.getSelection()Selection.removeAllRanges() を使用します。

HTML

html
<p id="p">
  <strong>以下のボタンを使用して</strong
  >この段落の内容を選択または選択解除してください。
</p>
<button id="select-button">段落を選択</button>
<button id="deselect-button">段落を選択解除</button>

JavaScript

js
const p = document.getElementById("p");
const selectButton = document.getElementById("select-button");
const deselectButton = document.getElementById("deselect-button");

selectButton.addEventListener("click", (e) => {
  // Clear any current selection
  const selection = window.getSelection();
  selection.removeAllRanges();

  // Select paragraph
  const range = document.createRange();
  range.selectNodeContents(p);
  selection.addRange(range);
});

deselectButton.addEventListener("click", (e) => {
  const selection = window.getSelection();
  selection.removeAllRanges();
});

結果

仕様書

Specification
DOM
# dom-range-selectnodecontents

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
selectNodeContents

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報