The insertBefore Method


The insertBefore Method

The 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

Method

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

insertBefore( node [, refNode ])

     

x

     

x

x

x

 

Returns: Node

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.



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