Node: replaceChild() method


目录

{{APIRef("DOM")}}

The replaceChild() method of the {{domxref("Node")}} interface replaces a child node within the given (parent) node.

Syntax

replaceChild(newChild, oldChild)

Parameters

[!NOTE] The parameter order, new before old, is unusual. Element.replaceWith(), applying only to nodes that are elements, may be easier to read and use.

Return value

The replaced {{domxref("Node")}}. This is the same node as oldChild.

Exceptions

Example

// Given:
// <div>
//  <span id="childSpan">foo bar</span>
// </div>

// Create an empty element node
// without an ID, any attributes, or any content
const sp1 = document.createElement("span");

// Give it an id attribute called 'newSpan'
sp1.id = "newSpan";

// Create some content for the new element.
const sp1Content = document.createTextNode("new replacement span element.");

// Apply that content to the new element
sp1.appendChild(sp1Content);

// Build a reference to the existing node to be replaced
const sp2 = document.getElementById("childSpan");
const 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

{{Specifications}}

Browser compatibility

{{Compat}}

See also


版本号 #2
由 壳壳虫 创建于 2026-10-31 03:27:53 UTC
由 壳壳虫 更新于 2026-10-31 03:27:53 UTC