SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Part II - W3C DOM Table of Contents : Building the Tree

To demonstrate how the table of contents works, let's examine a simple HTML fragment:

<H1>Header 1</H1>
...text...
<H2>Header 2</H2>
...text...

The first iteration of the getHeaders() function creates the following HTML fragment:

<UL>
  <LI CLASS="toc1">
    <A HREF="#destHeader1">
      Header 1
    </A>
  </LI>
</UL>

At the time the link to the destHeader1 is created, the HTML in the document is also updated with a bookmark destination:

<H1>
  <A ID="destHeader1"></A>
  Header 1
</H1>
...text...
<H2>Header 2</H2>
...text...

We are using the ID attribute to represent the destination rather than the name attribute. In HTML 4.0, the ID attribute is the recommended approach for specifying bookmarks within a document. We chose to use the HTML 4.0 approach since both Internet Explorer and Netscape Gecko support this feature. On the next iteration, the table of contents fragment is completed and another bookmark is inserted into the document:

<UL>
  <LI CLASS="toc1">
    <A HREF="#destHeader1">
      Header 1
    </A>
  </LI>
  <LI CLASS="toc2">
    <A HREF="#destHeader2">
      Header 2
    </A>
  </LI>
</UL>

and the HTML document is updated to:

<H1>
  <A ID="destHeader1"></A>
  Header 1
</H1>
...text...
<H2>
  <A ID="destHeader2"></A>
  Header 2
</H2>
...text...
The last step is to insert the table of contents fragment into the document. The actual insertion is done with the value returned by the getHeaders() function (see the complete script):
<UL>
  <LI CLASS="toc1">
    <A HREF="#destHeader1">
      Header 1
    </A>
  </LI>
  <LI CLASS="toc2">
    <A HREF="#destHeader2">
      Header 2
    </A>
  </LI>
</UL>
<H1>
  <A ID="destHeader1"></A>
  Header 1
</H1>
...text...
<H2>
  <A ID="destHeader2"></A>
  Header 2
</H2>
...text...

You now have a complete working table of contents. One advantage of using the W3C document object model is you can build complete fragments of HTML prior to inserting them into the document. In this example, the table of contents is created in memory element-by-element. Only when the table of contents is complete do we insert it into the document. On the next page, you can find the complete script for our live table of contents followed by a simple demonstration.