Click here to Skip to main content
15,795,793 members
Articles / Programming Languages / Javascript

Building a Table of Contents in JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 Jan 2016LGPL32 min read 15.8K   1   5
Building a table of contents in JavaScript

So you're publishing a long document online and don't have an easy mechanism to automatically add a table of contents on the server side? Well with JavaScript, you enslave the web browser to do it instead! This TOC generator...

  • needs no jQuery or other third-party library
  • creates links to each heading, adding an id attribute to each heading that doesn't already have one
  • can support pages that contain multiple content areas with multiple unrelated tables of contents


After installing the code below, call addTOC(contentElement, before, tocClass), where

  • contentElement is an element that contains the document or blog post for which you want a table of contents, and
  • before is an immediate child of contentElement; the table of contents will be inserted as a child of contentElement, just before before. before is optional and if unspecified, contentElement.firstChild is used.
  • tocClass is the CSS class of the table-of-contents blog (default value: "sidebox")

See example below.

The Code

Insert this code at the bottom of any page in which you want to add a TOC (before </body>).

<script>// Add table of contents! <![CDATA[
function $get(selector) { return document.querySelector(selector); };
function $all(selector) {

function buildTOC_ul(selector) {
      var levels=[document.createElement("ul"),null,null];
      var lvl=0, c=0;
      if (!selector) selector = "h2, h3, h4";
      $all(selector).forEach(function(el) {
            if (!'section_'+ ++c;
            var newLvl=(el.tagName=="H2"?0:el.tagName=="H3"?1:2);
            for (;lvl<newLvl;lvl++)

            var li=document.createElement('li');
            li.innerHTML="<a href='#""'></a>";
      return levels[0];
function addTOC(contentElement, before, tocClass) {
      if (before===undefined) before=contentElement.firstChild;
      var prefix = "";
        var c = contentElement.className;
        if (c) prefix="." + 
        (c.indexOf(" ")==-1?c:c.substr(0,c.indexOf(" "))) + " ";
      var selector = prefix+"h2, "+prefix+"h3, "+prefix+"h4";
      var toc=document.createElement("div");
      contentElement.insertBefore(toc, before);
// =========================
// =========================


The simplest thing you can do is to call addTOC(document.body), but that only works on very simple pages. Generally the page has a main content area; if you assign an id="content" to this content area, you can add the table of contents at the top like this:


(See definition of $get in the code above.) Here's how I'm calling addToc() on my blog:

var _post_ = $get("#post") || $get("#content");
addTOC(_post_, _post_.firstChild.nextSibling.nextSibling);

This allows the content area to have _post_.firstChild.nextSibling.nextSibling skip past the initial heading so that the table of contents is inserted underneath the heading.

Sidebar Style

The default class is sidebox, and if you insert the following CSS on your page, you will get a table of contents that floats beside the content, just as you see on this page.

.sidebox {
  border: 1px dotted rgb(127, 127, 127);
  padding: 4px 3px 4px 6px; /* top right bottom left */
  min-width: 100px ! important;
  float: right ! important;
  font-size: 90%;
  margin-top: 1px;
  margin-bottom: 1px;
  margin-left: 6px;
  visibility: visible;
  max-width: 50%;
  width: 35%;
.sidebox ul { padding:0em 0em 0em 1.3em; margin:0em; }//TRBL

Usage with GitHub Pages / Jekyll

If you're publishing with Jekyll, I suggest adding the above code to the bottom of /_layouts/default.html (and any other layouts you might use that might need a TOC, as long as they do not import default.html using a layout: default option), just before </body>, surrounded by a test like this:

{% if page.toc %}
var _post_ = $get("#post")||$get("#content");
addTOC(_post_, _post_.firstChild.nextSibling.nextSibling);
{% endif %}

This way, Jekyll only adds the TOC code to a page if the front-matter contains a toc: true option.

Original article published here.

This article was originally posted at


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Written By
Software Developer None
Canada Canada
Since I started programming when I was 11, I wrote the SNES emulator "SNEqr", the FastNav mapping component, the Enhanced C# programming language (in progress), the parser generator LLLPG, and LES, a syntax to help you start building programming languages, DSLs or build systems.

My overall focus is on the Language of your choice (Loyc) initiative, which is about investigating ways to improve interoperability between programming languages and putting more power in the hands of developers. I'm also seeking employment.

Comments and Discussions

QuestionWhat is this? Pin
Gerd Wagner15-Jan-16 4:07
professionalGerd Wagner15-Jan-16 4:07 
AnswerRe: What is this? Pin
Qwertie15-Jan-16 16:30
Qwertie15-Jan-16 16:30 

Whoops! A no-op! I'll delete it from the article.
toc.textContent = "Contents";

Okay, it's a little shorter, but in case you want to append without affecting existing content, wouldn't you still need appendChild(document.createTextNode(...))?

Notice that in modern HTML, we don't use h2|h3|... anymore, but rather nested sections with h1 titles

Uh... citation needed. This code would need modifications in about 3 places to support H1, which is assumed to be the title and therefore does not need to be part of the TOC.
GeneralRe: What is this? Pin
Gerd Wagner15-Jan-16 17:12
professionalGerd Wagner15-Jan-16 17:12 
GeneralRe: What is this? Pin
Qwertie15-Jan-16 19:57
Qwertie15-Jan-16 19:57 
GeneralMy vote of 5 Pin
Marc Clifton15-Nov-15 5:53
mvaMarc Clifton15-Nov-15 5:53 
GeneralMessage Closed Pin
17-Jan-16 3:11
Member 1089184817-Jan-16 3:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.