[thelist] TOC using DOM?

david.landy at somerfield.co.uk david.landy at somerfield.co.uk
Thu Jun 24 05:03:29 CDT 2004

Hi All,

I've got stuck trying to create an automatic Table-of-Contents (TOC) for my
page and I'd love some help.

What I've dfrom all the H1, H2, and H3 elements on a page.

I've written a javascript function that sifts through all the H1, H2, and H3
elements and makes anchors using the DOM, and hooked this function onto the
body.onload event.

So far so good, except for 2 small things:

1. My TOC appears at the end of the doc, not the top
2. It doesn't work!

It looks like all the elements are created correctly, but the <a name=xxx>
next to each <h1>, <h2> element don't receive the events targetted at them
eg <a href=#xxxx>, so there's no movement when you click.

Sorry if this description is a bit woolly I can't think how to phrase it
more clearly!

Any help appreciated.


//scan elements on the page and make a Table of Contents
function makeTOC() {
        Make a TOC

    var toc = "";

    if (!document.all)
        document.all = document.getElementsByTagName("*");

    var elem, i = 0;
    while (elem = document.all[i++]) {
        var oh, ih, newel;
        if ((elem.nodeName == "H1") || (elem.nodeName == "H2") ||
(elem.nodeName == "H3")) {
            ih = elem.innerHTML;
            newel = document.createElement("a name=\"" + ih + "\"");
            toc += "<li><a href=\"#" + ih + "\">" + ih + "</a>";
    toc = "<ul>" + toc + "</ul>";
    var newel = document.createElement("DIV");
    newel.innerHTML = toc;

The problem is that although the <a name=xxx> elements are created, they
don't receive events targetted 

If you are not the intended recipient of this e-mail, please preserve the
confidentiality of it and advise the sender immediately of any error in
transmission. Any disclosure, copying, distribution or action taken, or
omitted to be taken, by an unauthorised recipient in reliance upon the
contents of this e-mail is prohibited. Somerfield cannot accept liability
for any damage which you may sustain as a result of software viruses so
please carry out your own virus checks before opening an attachment. In
replying to this e-mail you are granting the right for that reply to be
forwarded to any other individual within the business and also to be read by
others. Any views expressed by an individual within this message do not
necessarily reflect the views of Somerfield.  Somerfield reserves the right
to intercept, monitor and record communications for lawful business

More information about the thelist mailing list