The Node.replaceChild() method replaces one child node of the specified node with another.


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.


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


Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Edge Opera Safari
Basic support 1.0 1.0 (1.7 or earlier)     IE6 (Maybe Earlier) (Yes) 1.0 (Yes)
Feature Android Webview Firefox Mobile (Gecko) IE Mobile Edge Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support (Yes) 1.0 (1) IE6 (Maybe Earlier) (Yes) 1.0 (Yes) 1.0

See also

Document Tags and Contributors

 Last updated by: djmarland,