HTML and CSS Reference
In-Depth Information
Each node can contain one or more child nodes . To reference the first child of the cur-
rent node, you use the following expression:
A document's root node
also can be referenced
using the documentEle-
ment object.
node .firstChild
In the node tree shown in Figure 14-7, the h1 node is the first child of the body node,
and the text node Dept. of History is its first (and only) child. All of the child nodes are
organized into the following object collection:
node .childNodes
As with other object collections, you can reference a particular object from this collec-
tion using the item's index number, as follows
node .childNodes[ i ]
where i is the index number of the child node.
To determine the total number of child nodes for a given node, you use the following
length property:
In an HTML document, the
order of the child nodes
matches the order of the
elements as they appear in
the file.
node .childNodes.length
For example, the length of the childNodes collection for the paragraph element in
Figure 14-7 is 3 (the two text nodes and the bold element). Figure 14-8 summarizes the
rest of the familial relationships in the node tree.
Figure 14-8
node relationships
The first child of node
node .firstChild
node .lastChild
The last child of node
node .childNodes
A collection of all of the nodes that are direct children of node
The sibling prior to node
node .previousSibling
node .nextSibling
The sibling after node
node .ownerDocument
The root node of the document
node .parentNode
The parent of node
Traversing the Element Nodes
The properties in Figure 14-8 make no distinction between nodes that represent elements
and nodes that represent other parts of the HTML document, such as text strings and
HTML comment tags. Thus, an expression such as node .childNodes.length returns
the number of child nodes of all types. If you're interested only in working with element
nodes, this property does not provide the information you need. Most browsers support
a collection of element node properties that provide information about element nodes
only. A list of these properties is shown in Figure 14-9.
Search WWH ::

Custom Search