Visit Mozilla.org

DOM:element.childNodes

From MDC

(Redirected from childNodes)

« Gecko DOM Reference

Contents

[edit] Summary

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

[edit] 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.

[edit] 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);
 };

[edit] 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.)

[edit] See Also

firstChild, lastChild and previousSibling

[edit] Specification