Our first task is to extract all the header (H1...H6) elements in the document. The
Internet Explorer model makes this extremely simple. In Internet Explorer the
document can be represented as a tree or a flattened collection of elements. The
flattened collection exposes easy access all elements through the
The W3C recommendation exposes the document primarily as a tree. In addition, a convenience method is exposed, getElementsByTagName, that can retrieve all the elements of a particular type in the document or all elements using a special wildcard identifier ("*"). Unfortunately, while IE5 supports this method, it does not support the wildcard value for returning all elements.
If we don't want to include any browser detection code, we can
write our own function for locating the headers. This script is not simple
and requires understanding recursion. Below is a basic function that
visits each element node in the document. On the last page we include an enhanced
version of this function that locates just the header elements and builds the TOC
on the fly.
Rather than deal with the complexity of this function, with a very simple script we can override IE5's incomplete support
for getElementsByTagName. A positive side-effect of this fix is we also add full support
for this method to Internet Explorer 4.0. With this small script we can make
IE5's implementation compatible with Netscape's. This also simplifies the script that
navigates to all elements. When examining the
The script for accessing all the elements is almost the same as
the script we would write using the original Internet Explorer model. The only difference
is we use the
We are going to continue with the simpler, non-recursive solution. We do provide the source code for both
solutions is provided at the end of this article.. Extracting the headers with getElementsByTagName() is simple.
We just examine all the element's in the document and check whether they are a header element:
Next we are going to process each header element when found and iteratively build the table of contents.
Page 1:W3C DOM Table of Contents
© 1997-2000 InsideDHTML.com, LLC. All rights reserved.