HTML and CSS Reference
In-Depth Information
forth. With that information, you can apply the following three rules to determine how a
new list item should be placed in the table of contents:
1. A list item at the same level as the previous item is simply appended to the current
ordered list.
2. A list item at a lower level than the previous item is placed in a new ordered list
that is nested within the current ordered list.
3. A list item at a higher level than the previous item is appended to the correspond-
ing ordered list higher up in the table of contents.
The key to these conditions is to record the previous item's level number. For that
purpose, you'll create a new variable named prevLevel , setting its initial value to 0. The
if condition to compare the value of nodeLevel to the level of the current node has the
following general form:
if (nodeLevel == prevLevel)
append the entry to the current list
else if (nodeLevel > prevLevel)
append the entry to a new nested list
else
append the entry to a higher-level list
You'll add these if conditions to the code of the createList() function now.
To add the if conditions:
1. Return to the toc.js file in your text editor.
2. Scroll down to the createList() function, and then add the following statements at
the start of the function to declare and set the initial value of the prevLevel vari-
able (see Figure 14-23):
/* Store the level of the previous list item
0 = top level, 1 = 2nd level, 2 = 3rd level, etc. */
var prevLevel = 0;
Figure 14-23
declaring the prevlevel variable
sets the initial value
of the prevLevel
variable to 0
3. Scroll down to the command block for the if condition and replace
TOCList.appendChild(listItem);
with the following if structure:
if (nodeLevel == prevLevel) {
/* Append the list item to the current list */
}
else if (nodeLevel > prevLevel) {
/* Start a new nested list */
}
else {
/* Append the list item to a higher nested list */
}
Search WWH ::




Custom Search