HTML and CSS Reference
In-Depth Information
The ordered list has been attached to the TOC box on the Web page. Next, you'll add
items to that list.
Working with Node Types, Names, and Values
The text for each entry in the table of contents needs to match the text of a heading ele-
ment in the source article. To do that, the TOC app will do the following:
1. Loop through the child nodes of the source article.
2. For each child node, test whether it represents a heading element.
3. If it is a heading element, extract the element's text and create a list item containing
that same text string.
4. Append the list item as a new child of the ordered list in the table of contents.
For simplicity's sake, we'll assume that each heading element is a direct child of the
article element in the HTML file rather than being nested within other elements, and
that the heading elements contain only text and no nested elements.
Looping Through a Child Node Collection
There are two ways of looping through a collection of child nodes. One approach uses a
counter variable that starts with a value of 0 and increases by 1 for each node, up to the
length of the childNodes collection. The general form of this loop is as follows:
for (var i = 0; i < node .childNodes.length; i ++) {
In this form, the child nodes in the for loop have the object reference
node .childNodes[ i ]
where node is the parent node of the child nodes collection, and i is the value of the
counter variable in the for loop.
The second approach uses familial references, starting with the first child of the parent
node and then moving to each subsequent sibling until no siblings remain. The general
form of this for loop is as follows:
for (var n = node .firstChild; n != null; n = n .nextSibling) {
In this form, the child nodes in the for loop have the following object reference:
When no next sibling is available, the value of n is equal to null and the loop stops.
Although both approaches yield the same results, using familial references has the
advantage that it does not require a browser to calculate the total length of the child
nodes collection. For large documents containing thousands of nodes, this can speed up
the processing time of the for loop. This method also provides the flexibility to insert
new nodes into a document within the for loop without having to recalculate the length
of the child nodes collection.
Search WWH ::

Custom Search