Removing Elements


list.removeChild(list.lastChild); 

The removeChild() method that every node has can be used to eliminate a node from the DOM tree. Note that you have to call this method from the parent element of the node to delete, and to provide the node as a parameter. The following sample shows a list and removes the last item every time the button is clicked; see Figure 5.3 for the output in the browser.

Removing Nodes (remove.html)

<script language="JavaScript"   type="text/javascript"> function removeItem() {   var list = document.getElementById("list");   if (list.childNodes.length > 0) {     list.removeChild(list.lastChild);   } } </script> <ol >   <li>Item</li>   <li>Item</li>   <li>Item</li>   <li>Item</li> </ol> <input type="button" onclick="removeItem();"   value="Remove item" /> 

Figure 5.3. The last node gets removed.


Tip

When you only have direct access to the node to delete (curNode in the following code), this approach will work:

curNode.parentNode.removeChild(curNode); 


When you call this code in a handler function for the node itself, you can replace curNode with this.





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