Java Reference
In-Depth Information
Navigating the DOM Tree
Node objects have a number of properties and methods for navigating around the document
tree. Once you have a reference to an element, you can walk along the document tree to find
other nodes. Let's focus on a particular part of the document tree in our example. The rela-
Figure 6.4. Navigating the DOM tree
The
childNodes
property is a list of all the nodes that are children of the node concerned.
The following example will return all the child nodes of the element with an
id
of
sports
:
var sports = document.getElementById('sports');
<< undefined
sports.childNodes;
<< NodeList [ #text "
", <p.swim>, #text "
", <p#bike>, #text "
", <p>, #text "
" ]
Note that the
childNodes
property returns
all
the nodes that are children of an element.
This will include any text nodes and since whitespace is treated as a text node, there will
often be empty text nodes in this collection.
The
children
property only returns any
element
nodes that are children of that node, so
will ignore any text nodes. Note that this is only supported in Internet Explorer from version
9 onwards:
