Daniel
Daniel

Reputation: 4342

javascript replacechild not working

I know this is an easy concept, but I just can't seem to get it working. Any ideas why? Here is my code:

var oldChild = document.getElementById("sbX1");
var newChild = document.createElement("div");
newChild.id= "sbYY1";
oldChild.replaceChild(newChild, oldChild);

Upvotes: 3

Views: 5128

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270637

You're calling replaceChild() on oldchild, when you ought to be calling it on the parent node of oldchild

var oldChild = document.getElementById("sbX1");
var newChild = document.createElement("div");
newChild.id= "sbYY1";

// Replace oldchild on the parent node
// You can reference the child's parent via .parentNode
// or retrieve it directly with document.getElementById('theparentId')
oldchild.parentNode.replaceChild(newChild, oldChild);

Upvotes: 9

Related Questions