I have headers in <h1> through <h6> tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well?
I would like the output to be something like:
<ol> <li>Header 1</li> <li>Header 1</li> <li>Header 2</li> <li>Header 3</li> </ol>
I am not currently using a JavaScript framework, but I don’t see why I couldn’t use one.
I am also looking for something done, since I’m guessing this is a common problem, but if not, a starting point to roll my own would be good.
I couldn’t resist putting together a quick implementation.
Add the following script anywhere on your page:
Your page should be structured something like this:
You can see it in action at https://codepen.io/scheinercc/pen/KEowRK (old link: http://magnetiq.com/exports/toc.htm (Works in IE, FF, Safari, Opera))