Mozilla.com

  1. MDC
  2. Main Page
  3. DOM
  4. element.childNodes

« Gecko DOM Reference

Summary

childNodes returns a collection of child nodes of the given element.

Syntax and values

var ndList = elementNodeReference.childNodes; 

ndList is an ordered collection of node objects that are children of the current element. If the element has no children, then ndList contains no node.

The ndList is a variable storing the node list of childNodes. Such list is of type NodeList. The childNodes attribute is read-only.

Example

// parg is an object reference to a <p> element
if (parg.hasChildNodes())
// So, first we check if the object is not empty, if the object has child nodes
 {
   var children = parg.childNodes;
   for (var i = 0; i < children.length; i++) 
   {
   // do something with each child as children[i]
   // NOTE: List is live, Adding or removing children will change the list
   };
 };
// This is one way to remove all children from a node
// box is an object refrence to an element with children
while (box.firstChild) 
 {
    //The list is LIVE so it will re-index each call
    box.removeChild(box.firstChild);
 };

Notes

The items in the collection of nodes are objects and not strings. To get data from those node objects, you must use their properties (e.g. elementNodeReference.childNodes[1].nodeName to get the name, etc.).

The document object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement. (In (X)HTML documents this is the HTML element.)

Page last modified 13:53, 10 Jul 2007 by Yaroukh?

Files (0)