JavaScript Table of Contents

In this post, we’re going to create a table of contents automatically with the JavaScript programming language. The table of contents helps the users of your website that read your post more easily.

What we are going to do?

We want to show a list of headings tags (h2,h3,h4,h5,h6) on the current page and when users click on it, users scroll to the head tag.

We use jQuery in this tutorial. So you need to include jQuery in your project.

Get Heading Tags

The first thing that we need to do is get the heading tags on the current page.

jQuery(document).ready(function($){
    function table_of_contents(){
        let get_headings = [$('h2'),$('h3'),$('h4'),$('h5'),$('h6')]
})

And now we should add a loop to get each head tag data like the innerText.

jQuery(document).ready(function($){
    let get_headings = [$('h2'),$('h3'),$('h4'),$('h5'),$('h6')]
    
    get_headings.forEach(heading =>{
        if(heading.length != 0){
            if(typeof heading == 'object'){
                for (let i = 0; i < heading.length; i++) {
                    const head = heading[i];
                    const URL = head.innerText.replace(/ /g,'_')
                    $(head).attr('id', URL)
                    const this_head = `<li><a href="#${URL}">${head.innerText}</a></li>`
                    $('your_id_or_class_here').append(this_head)
                    }
                }
            }
      })
})

Now if you call the table_of_contents() function you have an HTML like this.

Table of Contents HTML
Table of Contents HTML
<li><a href="#Heading_One">Heading One</a></li>
<li><a href="#Heading_Two">Heading Two</a></li>
<li><a href="#Heading_Three">Heading Three</a></li>

And you can show It next to the content of your website.