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.

句法

parentNode.replaceChild(newChild, oldChild);
					

参数

newChild
The new node to replace oldChild . If it already exists in the DOM, it is first removed.
oldChild

The child to be replaced.

返回值

The returned value is the replaced node. This is the same node as oldChild .

范例

// 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>
					

规范

规范 状态 注释
DOM
The definition of 'Node: replaceChild' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
replaceChild Chrome 1 Edge 12 Firefox 1 IE 9 Opera 7 Safari 1.1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: