HTML and CSS Reference
In-Depth Information
To apply the indexOf() function:
1. Scroll down to the createList() function and insert the following code, as shown in
Figure 14-19:
/* Determine the heading level (if any) of the current node */
var nodeLevel = headings.indexOf(n.nodeName);
Figure 14-19
determining the level of the heading
the nodeLevel variable
will have a value of 0
through 5 for h1
through h6 headings
and -1 for all other
element nodes
2. Save your changes to the file.
Next, you'll add code to test the value of the nodeLevel variable. If it is not equal to
-1, the code will create a new list item for the TOC containing the text of the heading
and then append it to the table of contents.
To create a list item for each heading:
1. Add the following command to the for loop in the createList() function, as shown
in Figure 14-20:
/* If the node comes from a heading element, create a list item
and append it to the TOC */
if (nodeLevel != -1) {
var listItem = document.createElement(“li”);
listItem.innerHTML = n.innerHTML;
Figure 14-20
appending a list item to the tOc
creates and appends
a list item for every
element node that
acts as a heading
Search WWH ::

Custom Search