227Chapter 15Generic HTML Element ObjectsA child nodeis (Free web hosting with ftp) an
227Chapter 15Generic HTML Element ObjectsA child nodeis an element that is contained by another element. The container is the parentof such a child. Just as an HTML element can contain any number of child elements, so can aparent object have zero or more children. A list of those children (returned as an array) canbe read from an object by way of its childNodesproperty: var nodeArray = document.getElementById( elementID ).childNodes; While you can use this array (and its lengthproperty) to get a reference to the first or lastchild node, the firstChildand lastChildproperties offer shortcuts to those positions. These are helpful when you wish to insert a new child before or after all of the others and youneed a reference point for the IE insertAdjacentElement()method or other method thatadds elements to the document s node list. ExampleListing 15-10 contains an example of how to use the firstChildand lastChildpropertiesto access child nodes. These two properties come in handy in this example, which adds andreplaces lielements to an existing olelement. You can enter any text you want to appear atthe beginning or end of the list. Using the firstChildand lastChildproperties simplifiesaccess to the ends of the list. For the functions that replace child nodes, the example uses thereplaceChild()method. Alternatively for IE4+, you can modify the innerTextproperty ofthe objects returned by the firstChildor lastChildproperty. This example is especiallyinteresting to watch when you add items to the list: The browser automatically renumbersitems to fit the current state of the list. See the discussion of the childNodesproperty earlier in this chapter about the presence of phantom nodes in some browser versions. The problem may influence your use of thefirstChildand lastChildproperties. Listing 15-10: Using firstChild and lastChild Properties