Adding Elements


list.appendChild(newNode); 

Creating new DOM nodes is done by the document.createElement() method. It creates a new element, using the tag name provided as a parameter. This element can then be inserted into the DOM tree. The (node) method that is used most of the time is appendChild(). It appends a new child to the end of the children list.

The following code adds a new, empty list element (<li>) to the end of the <ul> list whenever the button is clicked:

Adding Nodes (add.html)

<script language="JavaScript"   type="text/javascript"> function addItem() {   var list = document.getElementById("list");   var newNode = document.createElement("li");   list.appendChild(newNode); } </script> <ul ><li>Item</li></ul> <input type="button" onclick="addItem();"   value="Add item" /> 

The disadvantage of this approach is that the new element is always appended to the end of the children list. To mitigate this effect, the insertBefore() method allows inserting a new node before any other node (so you can insert it anywhere but at the end of the listyou still have appendChild() for this). As in parameters, you provide the new node first, then the new sibling.

The following code inserts a new <li> element to the beginning of the list anytime the button is clicked. This is documented in Figure 5.4.

Adding Nodes at the Beginning of the Children List (addbefore.html)

<script language="JavaScript"   type="text/javascript"> function addItem() {   var list = document.getElementById("list");   var newNode = document.createElement("li");   list.insertBefore(newNode, list.firstChild); } </script> <ul ><li>Item</li></ul> <input type="button" onclick=vaddItem();"   value="Add item" /> 

Figure 5.4. List elements are added to the beginning of the list.





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