ChildNode.replaceWith() - Web APIs 编辑
The ChildNode.replaceWith()
method replaces this ChildNode
in the children list of its parent with a set of Node
or DOMString
objects. DOMString
objects are inserted as equivalent Text
nodes.
Syntax
[Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes);
Parameters
Exceptions
HierarchyRequestError
: Node cannot be inserted at the specified point in the hierarchy.
Examples
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
The replaceWith()
method is not scoped into the with
statement. See Symbol.unscopables
for more information.
with(node) {
replaceWith("foo");
}
// ReferenceError: replaceWith is not defined
Polyfill
You can polyfill the replaceWith()
method in Internet Explorer 10+ and higher with the following code:
function ReplaceWithPolyfill() {
'use-strict'; // For safari, and IE > 10
var parent = this.parentNode, i = arguments.length, currentNode;
if (!parent) return;
if (!i) // if there are no arguments
parent.removeChild(this);
while (i--) { // i-- decrements i and returns the value of i before the decrement
currentNode = arguments[i];
if (typeof currentNode !== 'object'){
currentNode = this.ownerDocument.createTextNode(currentNode);
} else if (currentNode.parentNode){
currentNode.parentNode.removeChild(currentNode);
}
// the value of "i" below is after the decrement
if (!i) // if currentNode is the first argument (currentNode === arguments[0])
parent.replaceChild(currentNode, this);
else // if currentNode isn't the first
parent.insertBefore(currentNode, this.nextSibling);
}
}
if (!Element.prototype.replaceWith)
Element.prototype.replaceWith = ReplaceWithPolyfill;
if (!CharacterData.prototype.replaceWith)
CharacterData.prototype.replaceWith = ReplaceWithPolyfill;
if (!DocumentType.prototype.replaceWith)
DocumentType.prototype.replaceWith = ReplaceWithPolyfill;
Specifications
Specification | Status | Comment |
---|---|---|
DOM The definition of 'ChildNode.replacewith()' in that specification. | Living Standard | Initial definition. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论