The Node.replaceChild() method replaces a child node within the given (parent) node.

Syntax

replacedNode = parentNode.replaceChild(newChild, oldChild);
  • newChild is the new node to replace oldChild. If it already exists in the DOM, it is first removed.
  • oldChild is the existing child to be replaced.
  • replacedNode 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> 

Specification

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support 1Edge Full support YesFirefox Full support 1IE Full support 6Opera Full support 2Safari Full support YesWebView Android Full support 1Chrome Android Full support 18Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

See also

Document Tags and Contributors

Last updated by: mfluehr,