HTML and CSS Reference
In-Depth Information
In some cases, you need to determine whether an element has a particular attribute,
such as the id attribute. In these situations, you use the hasAttribute() method, which
returns the Boolean value true if the element contains the attribute. For example, the
would return the value true if the list item had an id attribute, and would return false
Setting the Heading Element ids
Now that you've learned how to work with attributes, you'll insert id attributes into all
of the heading elements in the source document. Because each id must be unique, you'll
create a counter variable named entryNum that increases by 1 for each TOC heading
found in the source document. You'll declare the entryNum variable now, setting its
initial value to 0.
To create the counter variable:
1. Return to the toc.js file in your text editor.
2. Within the createList() function, insert the following code directly after the com-
mand to declare the prevLevel variable (see Figure 14-36):
/* Keep a running count of the TOC entries from
the source document */
var entryNum = 0;
Figure 14-36
declaring the entrynum variable
Next, use the entryNum variable to write the id of each heading element. Each id
value will have the form
heading if
where if is the value of the entryNum variable. You must be careful not to overwrite any
preexisting ids. Therefore, your code should first test whether an id already exists for the
element and insert an id attribute only if it doesn't.
To write the heading id values:
1. Directly after the if condition that tests whether the value of the nodeLevel vari-
able is not equal to -1, insert the following commands (see Figure 14-37):
/* Add an id attribute to the element to be used
as the target of a hypertext link */
if ( == “”) = “heading” + entryNum;
Search WWH ::

Custom Search