这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
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]);
规范
规范 | 状态 | 注释 |
---|---|---|
DOM ChildNode.replacewith() |
Living Standard | Initial definition. |
浏览器兼容性
Update compatibility data on GitHub
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
replaceWith | Chrome Full support 54 | Edge Full support 17 | Firefox Full support 49 | IE No support No | Opera Full support 39 | Safari Full support Yes | WebView Android Full support 54 | Chrome Android Full support 54 | Firefox Android Full support 49 | Opera Android Full support 41 | Safari iOS Full support Yes | Samsung Internet Android Full support 6.0 |
Legend
- Full support
- Full support
- No support
- No support