Element.replaceWith()
Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
ChildNode.replaceWith()
的方法用一套 Node
对象或者 DOMString
对象,替换了该节点父节点下的子节点。DOMString
对象被当做等效的Text
节点插入。
语法
[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