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.
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.
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:
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!