Element: replaceWith() 方法

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有瀏覽器中可用。

Element.replaceWith() 方法使用一組 Node 物件或字串替換父級子節點列表中的此 Element。字串會被插入為等效的 Text 節點。

語法

js
replaceWith(param1)
replaceWith(param1, param2)
replaceWith(param1, param2, /* …, */ paramN)

引數

param1, …, paramN

用於替換的 Node 物件或字串集合。

返回值

無(undefined)。

異常

HierarchyRequestError DOMException

在節點無法插入到層次結構中的指定位置時丟擲。

示例

使用 replaceWith()

js
const div = document.createElement("div");
const p = document.createElement("p");
div.appendChild(p);
const span = document.createElement("span");

p.replaceWith(span);

console.log(div.outerHTML);
// "<div><span></span></div>"

replaceWith() 是不可作用域的

replaceWith() 方法不會被 with 語句作用域。有關更多資訊,請參閱 Symbol.unscopables

js
with (node) {
  replaceWith("foo");
}
// ReferenceError: replaceWith is not defined

規範

規範
DOM
# ref-for-dom-childnode-replacewith①

瀏覽器相容性

另見