[Javascript] How to Make a Table of Contents Automatically

table of contents


In this article, we will describe about how to automatically generate a Table of Contents (toc) from headings using Javascript.
Our method also supports multiple levels of headings.



Table of Contents from Headings

We aim to automatically generate a table of contents from headings, assuming the presence of HTML as below.
The table of contents will be inserted just before the first heading tag.

<h1>Page Title</h1>
<div id="content">
    <h2>heading1</h2>
    <h3>subheading1</h3>
    <h3>subheading2</h3>
    <h4>sub-subheading1</h4>
    <h5>sub-sub-subheading1</h5>
    <h3>subheading3</h3>
    <h2>heading2</h2>
    <h3>subheading1</h3>
</div>





Script to generate a Table Of Contents

The JavaScript for automatically generating a table of contents from headings is as follows.
It also provides anchor links to enable jumping from the table of contents to the headings.

const toc = '<div id="toc"><p>Table of Contents</p><ul></ul></div>'     // Structure of the table of contents
const target = '#content h2, #content h3, #content h4, #content h5'     // Target heading element

document.querySelector(target).insertAdjacentHTML('beforebegin', toc)   // Add the structure to the DOM
document.querySelectorAll(target).forEach((h, i) => {
    const id = `toc-${i}`                                               // ID for anchor link
    const text = h.textContent                                          // Text for table of contents list
    const attr = `class="toc-${h.tagName}"`                             // Attribute for table of contents list
    const list = `<li ${attr}><a href='#${id}'>${text}</a></li>`        // Table of contents list(anchor link)
    document.querySelector('#toc ul').innerHTML += list                 // Add table of contents list 
    h.setAttribute('id', id)                                            // Assign an ID to the heading(for anchor link)
})


The table of contents will be output as follows.
Now, let’s adjust the appearance and make the hierarchy more visually organized.





Clarify the hierarchy of the Table Of Contents

All that’s left is to style it as you like. I’ll provide a sample CSS.
Tthe previous script have added classes like “toc-H3” to the list elements of the table of contents, making it easier to style hierarchically.

#toc .toc-H3 { margin-left: 15px }
#toc .toc-H4 { margin-left: 30px }
#toc .toc-H5 { margin-left: 45px }
#toc .toc-H6 { margin-left: 60px }
#toc {
    border: 3px #BDBDBD solid;
    padding: 30px;
    margin: 50px 0;
}
#toc p {
    font-weight: bold;
    font-size: 24px;
    margin-bottom: 10px;
}
#toc a{
    font-size: 16px;
    color: inherit;
}
#toc ul {
    padding-left: 20px;
}
#toc li {
    line-height: 1.8;
}


The hierarchy is now more clear.





Include only h2 in the Table Of Contents

Earlier, we included headings from h2 to h5 in the table of contents.
You can adjust which heading levels to include by modifying the following part of the JavaScript as needed.

const target = '#content h2, #content h3, #content h4, #content h5'


By making the following change, you can limit the table of contents to only include h2.

const target = '#content h2'

Table of Contents







That is all, it was about how to automatically generate Table of Contents from headings using Javascript!

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*