The insertBefore MethodThe insertBefore method enables you to insert a W3C node before another node. You can see the support for this method in Table 6.31. Table 6.31. The insertBefore Method
Here, you pass the node you want to insert, and a reference node . The reference is a child node of the current node, and the new node is inserted directly before the reference node. If the reference node is missing or null, the node is added as the last child node of the current node. This method returns the node that was inserted. We'll see more on methods such as this one in Chapter 16, but here's an example where I'm creating a new <DIV> element using the document object's createElement method (which returns an element object that you also can treat as a node) and adding other objectstext and a text fieldto that element using insertBefore : (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> This code gives you the same result you see in Figure 6.6. |