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.


let oldChild = parentNode.replaceChild(newChild, oldChild);


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

Return value

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' = "newSpan";

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

// Apply that content to the new element

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


Specification Status Comment
The definition of 'Node: replaceChild' in that specification.
Living Standard

Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
replaceChildChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 7Safari Full support 1.1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0


Full support  
Full support

See also