JavaScript document map

JavaScript code to generate a document map/table of contents from the document structure.

NB – Sorry I need to update this to get the examples working in WordPress

This page generates the following document map:


You’ll want a target div for the table of contents somewhere on your page:

Then call the function at the end of a page or stick a window.onload function in:


The parameters are pretty straight forward:

1 will take everything in the body of the document
0 if you are going to pass HTML in
The HTML you want it to use if you aren’t using the whole document. If you aren’t passing any in, just leave it blank – “”. You can just pass in the html of a particular div like this: document.getElementById(“a_div”).innerHTML. I should probably change it so you can just pass a div ID in..
1 if you want the document map hyper-linked to the headings. (This will add anchors at the heading elements).
0 will just give a plain text listing.
The first item in the listing will be a heading, followed by nested lists. This sets the heading level you want it to be. (most likely 2 or 3). The default is 3.
If you set this to 1 it will add the heading level to the end of the link (like in the example on this page.
0 will leave it off

It would probably be better to replace use_body with an element ID and do it that way, but I haven’t got round to doing that yet..


Some headings just to show how the toc works.

A heading

Blah blah blah

A sub heading

Blah blah blah

Another sub heading

Another sub heading
Another sub heading

Another heading

Another sub heading

A bad heading structure

One thought on “JavaScript document map

Leave a Reply

Your email address will not be published.