HTML and CSS Reference
In-Depth Information
Don't worry that the other headings are missing from the table of contents. At this
point, the createList() function only works going across the current level or down to the
next level of headings. There are no commands to go up to the nested list of items for the
higher-level headings. You'll add commands to handle that condition next.
When moving up one or more levels in the table of contents, you'll append the new
list item to a preexisting list. Figure 14-30 shows an HTML fragment and the correspond-
ing node tree for adding a new list item to a higher-level list.
Figure 14-30
appending an item to an upper-level list
<ol>
<li>h1 text</li>
<li>h1 text
<ol>
<li>h2 text</li>
<li>h2 text
<ol>
<li>h3 text</li>
<li>h3 text</li>
<li>h3 text</li>
</ol>
</li>
</ol>
</li>
<li>h1 text</li>
</ol>
OL
LI
LI
LI
"h1 text"
"h1 text"
"h1 text"
OL
LI
LI
"h2 text"
"h2 text"
OL
LI
LI
LI
"h3 text"
"h3 text"
"h3 text"
HTML fragment
corresponding node tree
The challenge is to calculate how many levels to go up in the node tree to find the
correct list. Examine Figure 14-31 and notice that for each level you go up in the section
headings, you go up two levels in the node tree—past the parent
ol
element and then
past that element's
li
parent. For example, to go from
h3
headings back up to
h1
head-
ings, you go up four levels in the node tree. Thus, you must first calculate the difference
between the current heading level and the level of the new entry, which is simply the
difference between the
prevLevel
variable and the
nodeLevel
variable. You can store that
difference in the following
levelUp
variable:
var levelUp = prevLevel - nodeLevel;
To move up the node tree, you apply the
parentNode
property twice for each difference in
level between the two headings. That approach can be placed in the following
for
loop:
for (var i = 1; i <= levelUp; i++) {
TOCList = TOCList.parentNode.parentNode;
}
On each iteration, the
for
loop changes the table of contents list to the TOC list two lev-
els up on the node tree. The loop stops when it has gone up the correct number of levels
as indicated by the
levelUp
variable. Once you're at the correct level, you'll append the
new list item to the table of contents list, as follows:
TOCList.appendChild(listItem);
You'll add these commands to the
else
condition in the changeList() function now.