HTML and CSS Reference
In-Depth Information
Traversing the Node Tree with Recursion
In creating the dynamic table of contents, you made several simplifying assumptions.
One was that all of the section headings in each historic document would be siblings
and children of the source document. You did not allow for the possibility that a sec-
tion heading would be further nested within another element. However, some applica-
tions that involve working with the node tree require a script to traverse the entire tree,
touching each node. One way of doing this is through recursion. Recursion is a program-
ming technique in which a function calls itself repeatedly until a stopping condition is
met. The following is an example of a recursive function that counts the number of child
nodes descending from a given node:
function countNodes(node, nodeCount) {
for (var n = node.firstChild; n != null; n = n.nextSibling) {
countNodes(n, nodeCount);
return nodeCount;
Notice that the countNodes() function includes a for loop that loops through every
child node of the given node object. For each child node the function finds, it increases
the value of the nodeCount parameter by 1 and then calls itself to add the number of
children of that child node to the total. Then, for each child node in that set, it calls the
countNodes() function again to count the number of children in the next lower level. This
process of drilling down the node tree continues until no descendant nodes remain in
the node tree.
Every recursive function needs a starting point. If you wanted to count all of the nodes
in Norene's source article, you would point the node parameter to the source article and
set the initial value of the nodeCount variable to 0. The expression to count all of the
nodes would be as follows:
countNodes(source, 0)
If you applied this command to Norene's U.S. Constitution document, you would dis-
cover that the document contains 441 nodes composed of text nodes, element nodes,
and white space nodes.
Creating a Style Sheet Switcher
Norene is pleased with all of the work you have done on the dynamic table of contents.
She has created three style sheets to view the U.S. Constitution in forms suitable for the
Web—the style sheet you've been working with—as well as for printing and for users
who want a large text rendition. Figure 14-58 shows the page layout and appearance
under each style sheet.
Search WWH ::

Custom Search