Replacing Elements


list.replaceChild(newNode, list.firstChild); 

If you remove a node and then insert another one at the same place, the replaceChild() method saves you a bit of coding. You provide the new and the old node, and JavaScript does the rest for you. Remember that you have to call this method from the parent element of the old and the new node!

Replacing Nodes (replace.html)

<script language="JavaScript"   type="text/javascript"> var nr = 1; function addItem() {   var list = document.getElementById("list");   var newNode = document.createElement("li");   nr++;   var newTextNode =     document.createTextNode("Item " + nr);   newNode.appendChild(newTextNode);   list.replaceChild(newNode, list.firstChild); } </script> <ul ><li>Item 1</li></ul> <input type="button" onclick="addItem();"   value="Replace item" /> 

The preceding code replaces the first child (node) of the list with a new node.




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net