The appendChild Method


The appendChild Method

The appendChild method enables you to append a child HTML element (not a node) to another HTML element. You can see the support for this method in Table 6.7.

Table 6.7. The appendChild Method

Method

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

appendChild (node)

     

x

     

x

x

x

 

Returns: Node

We'll see more about methods like this, which enable you to change the structure of a document on-the-fly, in Chapter 16, "Dynamic HTML: Changing Web Pages On-the-Fly ." Here's an example that uses the appendChild method to add a new item to an unordered HTML list, and the replaceChild method (coming up later in this chapter) to replace the first item in the list. When the user clicks the Add New Item button, the appendChild method adds a new item to an unordered HTML list:

(Listing 06-03.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the appendChild and replaceChild Methods          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function adder()   {   var item1 = document.createElement("LI")   item1.innerHTML = "Next item"   document.getElementById("list1").appendChild(item1)   }  function replacer(form)              {                  var item1 = document.createElemnt("LI")                  item1.innerHTML = "Newer First Item"                  var lastItem = document.getElementById("list1").firstChild                  document.getElementById("list1").replaceChild(item1, lastItem)              }              -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Using the appendChild and replaceChild Methods</H1>          <FORM>  <INPUT TYPE=BUTTON VALUE="Add New Item" onclick="adder()">  <INPUT TYPE=BUTTON VALUE="Replace First Item" onclick="replacer()">          </FORM>          <UL ID="list1">              <LI>First Item              <LI>Second Item          <UL>      </BODY>  </HTML> 

You can see the results in Figure 6.4. Originally, the list only had two items, First Item and Second Item; but when you click the Add New Item button, the code adds a new item, Next Item, to the list.

Figure 6.4. Using the appendChild and replaceChild Methods.

graphics/06fig04.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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