Range:surroundContents() 方法

Baseline 已廣泛支援

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

surroundContents() 方法是 Range 介面的一部分,它使用提供的節點來包裹選中的內容。該方法會 提取 選區的內容,用提取的內容替換 newParent 的子節點,將 newParent 插入 到提取內容的原位置,並使選區選中 newParent

如果選區部分包含任何非 Text 節點,則會丟擲異常。選區只能包含文字節點和完全選中的節點。

語法

js
surroundContents(newParent)

引數

newParent

用於包裹內容的 Node

返回值

無(undefined)。

示例

HTML

html
<span class="header-text">Put this in a headline</span>

JavaScript

js
const range = document.createRange();
const newParent = document.createElement("h1");

range.selectNode(document.querySelector(".header-text"));
range.surroundContents(newParent);

結果

規範

規範
DOM
# dom-range-surroundcontents

瀏覽器相容性

另見