There are plenty of jQuery plugins available that can generate a Table of Contents on an HTML page. I wanted to roll my own simple script with a few lines of jQuery.
<h1>elements inside a container (
#blogContents) on the page
As I mentioned, this plugin will use jQuery, so include that to start.
<h1>we set a variable that gets the id and the text inside the tag.
<a>) for each, setting the href, title and text attributes.
<a>to a list item (
<ul>container element - this gives us our list of contents.
Make sure you include the
<ul> container in your page where you want your ToC to appear.
If you don’t have any
<h1> tags in your container you will end up with an empty
<ul> container sitting on your page. If you don’t want that, you can alternatively check to see if the page conatins any h1 elements, if there are, the following script will create the ToC container automatically - ready for your list of contents to be appended.
If you use this method, you need to make sure that this script runs BEFORE we generate the list of contents.
See the Pen Quick and Dirty Table of Contents with jQuery (ToC) by Matthew Elsom (@matthewelsom) on CodePen.