1. Home
  2. Computing & Technology
  3. JavaScript

The Javascript DOM

13. replaceChild

clr gif

With what we have already covered in these tutorials you already know how to effectively replace a container in our web page with a different newly created one. We could do it using the code from pur last tutorial to insert the new object and then use the deleteChild method that we looked at earlier to delete the container that is being replaced.

That does it in two steps. The new paraghraph will be added to the page and then the old paragraph will be deleted. What would be better would be to do it in one step and that is where the replaceChild method comes in. Simply by substituting replaceChild for insertBefore we can replace the existing object instead of adding in front of it.

var newP = document.createElement("p");
var txt = 'Kilroy was here.';
var newT = document.createTextNode(txt);
newP.appendChild(newT);
var p2 = document.getElementsByTagName('p')[1];
p2.parentNode.replaceChild(newP,p2);

By using one step instead of two to update the content of the page we get the change to appear in one go instead of having the new paragraph appear first and then the old one disappearing.

Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.