Element.replaceWith()
语法
[Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes);
参数
例外
HierarchyRequestError
: 无法在层次结构中的指定点插入节点。
案例
Using replaceWith()
var parent = document.createElement("div");
var child = document.createElement("p");
parent.appendChild(child);
var span = document.createElement("span");
child.replaceWith(span);
console.log(parent.outerHTML);
// "<div><span></span></div>"
ChildNode.replaceWith()
is unscopable
replaceWith()
的方法并没有作用于 with 语句。参考 Symbol.unscopables
获取更多信息。
with(node) {
replaceWith("foo");
}
// ReferenceError: replaceWith is not defined
Polyfill
你可以在 IE9 及更高级的浏览器中使用下面的代码向上兼容replaceWith()
的方法:
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('replaceWith')) {
return;
}
Object.defineProperty(item, 'replaceWith', {
configurable: true,
enumerable: true,
writable: true,
value: function replaceWith() {
var argArr = Array.prototype.slice.call(arguments),
docFrag = document.createDocumentFragment();
argArr.forEach(function (argItem) {
var isNode = argItem instanceof Node;
docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
});
this.parentNode.replaceChild(docFrag, this);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
规范
Specification |
---|
DOM Standard # ref-for-dom-childnode-replacewith① |
浏览器兼容性
BCD tables only load in the browser