Range:selectNodeContents() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Range.selectNodeContents() 方法將 Range 設定為包含一個 Node 的內容。

開始和結束 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>Use the buttons below</strong> to select or deselect the contents of
  this paragraph.
</p>
<button id="select-button">Select paragraph</button>
<button id="deselect-button">Deselect paragraph</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();
});

結果

規範

規範
DOM
# dom-range-selectnodecontents

瀏覽器相容性

另見