Milan Lund logo

Hi, I am Milan Lund!Full Stack Web Developer

I specialise in building websites and web applications with and Kentico platforms.

  • Front-end

Table of contents in Javascript

In this post, I will provide you with a javascript code sample that transforms headings in a page into a structured table of contents with anchor links.

When writing a long structured article, it is always handy for your readers having a table of contents that helps them navigate through it. I composed a javascript code sample that creates such a table of contents on the fly for you. It iterates through the article headings and 

  • creates anchors for each of them and 
  • renders a structured unordered list with anchor links.

Here is a link to a working demo on Codepen.

How to make it work?

  1. In your markup, create an empty ul element (i.e. <ul class="table-of-contents"></ul>) that will stand for the table of contents. 
  2. Copy the Javascript code from the pen or code block below into your project. I wrote the code in ES6 so that you may need to transpile it into ES5 in case you need to use the functionality on the client side. Babel could be a great choice.
  3. When calling the tableOfContents function, pass the settings object with selectors for 
    • the headings you want to be part of the table of contents (headingsSelector property) and 
    • the table of contents wrapper you've created in the first step (wrapperSelector property).

The code

Working demo on Codepen