The appendChild MethodThe 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
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.
|