Generate TOC with Javascript
I had to generate a table of contents based on the contents of an article. So what´s the smiplest way?
I had two ways to go:
- Parse the HTML (should be XHTML, which allows me to use an XMLDocument for example), but it could also be ugly HTML.
- Read the DOM with javascript and generate links for each header in the article.
Since I don´t know if it is valid XHTML I choosed alternative #2 which is with Javascript.
The article contains headers which are h2, the text between can contain different html tags, but the headers are always h2.
First I created a div tag with the id set to "contents" which will contain the table of contents, and after that I created a div with the id set to "article" and which contains the article.
Now when I have the containers I could easily use javascript to get the titles and generate a list with the anchors to the headers.
I created a function CreateTOC(headerText) that can be use to generate the TOC. The parameter headerText is the value of the header that´s created (you should always have a h2 or higher just before a list for higher usability).
You can see the result here:
http://dev.mikaelsoderstrom.se/scripts/javascript/generatetoc.html
If you want to use it, just take it, but please leave the copyright. ![]()
If you modify it or have tips on how to make it better, please let me know!