You can use document methods such as createElement and createTextNode (in IE4+ and NS6+) to create and insert new elements in a document, using methods such as the insertBefore method, as we'll see in Chapter 16. Actually, we've already put these methods to work a while ago in Chapter 6see "The insertBefore Method" in that chapter. There, I created a new element, created a new text node to hold the text in the element, and then used insertBefore to insert the new element into the web page. Here's what that code looked like (Listing 06-09.html on the web site): <HTML> <HEAD> <TITLE> Creating New Elements </TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function addMore() { var newDiv, newTextField, newText newDiv = document.createElement("DIV") newTextField = document.createElement("INPUT") newTextField.type = "TEXT" newTextField.value = "Hello!" newText = document.createTextNode("Here is a new text field: ") newDiv.insertBefore(newText, null) newDiv.insertBefore(newTextField, null) document.body.insertBefore(newDiv, null) } // --> </SCRIPT> </HEAD> <BODY> <H1>Creating New Elements</H1> <FORM> <INPUT TYPE=BUTTON VALUE="Click Me!" ONCLICK="addMore()"> </FORM> </BODY> </HTML> Each time you click the button in this example, a new <DIV> element is created with some text in it, as well as a text field element. You can see the results of this code in Chapter 6, in Figure 6.6. |