Node.replaceChild() - Web APIs 编辑
The Node.replaceChild()
method replaces a child node within the given (parent) node.
Note the idiosyncratic argument order (new before old). ChildNode.replaceWith()
may be easier to read and use.
Syntax
let oldChild = parentNode.replaceChild(newChild, oldChild);
Parameters
- newChild
- The new node to replace
oldChild
. If it already exists in the DOM, it is first removed. - oldChild
- The child to be replaced.
Return value
The returned value is the replaced node. This is the same node as oldChild
.
Example
// Given:
// <div>
// <span id="childSpan">foo bar</span>
// </div>
// Create an empty element node
// without an ID, any attributes, or any content
var sp1 = document.createElement("span");
// Give it an id attribute called 'newSpan'
sp1.id = "newSpan";
// Create some content for the new element.
var sp1_content = document.createTextNode("new replacement span element.");
// Apply that content to the new element
sp1.appendChild(sp1_content);
// Build a reference to the existing node to be replaced
var sp2 = document.getElementById("childSpan");
var parentDiv = sp2.parentNode;
// Replace existing node sp2 with the new span element sp1
parentDiv.replaceChild(sp1, sp2);
// Result:
// <div>
// <span id="newSpan">new replacement span element.</span>
// </div>
Specifications
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Node: replaceChild' in that specification. | Living Standard |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论