DOM
ChildNode.replaceWith() 的方法用一套 Node 对象或者字符串对象,替换了该节点父节点下的子节点。字符串对象被当做等效的 Text 节点插入。
语法
replaceWith(param1)
replaceWith(param1, param2)
replaceWith(param1, param2, /* …, */ paramN)
参数
param1、…、paramN- : 一系列用来替换的 Node 对象或者字符串对象。
异常
HierarchyRequestErrorDOMException- : 无法在层次结构中的指定节点处插入节点时抛出。
示例
使用 replaceWith()
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 获取更多信息。
with (node) {
replaceWith("foo");
}
// ReferenceError: replaceWith is not defined
规范
浏览器兼容性
参见
- Node.replaceChild()
- NodeList
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
