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①

浏览器兼容性

另见