Build a Dynamic Table of Contents with jQuery

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.

Objectives

  • Dynamically create a Table of Contents (ToC) at the top of my HTML page
  • Link the ToC items to any <h1> elements inside a container (#blogContents) on the page
  • Assumption: H1 elements always have an id attribute (as they are generated using Jekyll)

Writing the script

As I mentioned, this plugin will use jQuery, so include that to start.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • Start by finding all the h1 elements inside the #blogContents container.
  • For each <h1> we set a variable that gets the id and the text inside the tag.
  • Then, we can write a string that generates a link (<a>) for each, setting the href, title and text attributes.
  • Append each <a> to a list item (<li>).
  • The list items are then appended into a specified <ul> container element - this gives us our list of contents.
  $('#blogContents').find('h1').each(function() {
    var $item = $(this);
    var $id = $(this).attr('id');
    var li = $('<li/>');
    var a = $('<a/>', {text: $item.text(), href: '#' + $id, title: $item.text()});
    a.appendTo(li);
    $('#blogContents .toc ul').append(li);
  });

Make sure you include the <ul> container in your page where you want your ToC to appear.

<div id="blogContents">
  <ul class="toc"></ul>
  ...
</div>

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 ($('#blogContents h1').length > 0) {
  $('#blogContents').prepend('<nav class="toc"><h3 class="title">Table of Contents</h3><ul></ul></nav>');
}

If you use this method, you need to make sure that this script runs BEFORE we generate the list of contents.

Demo

See the Pen Quick and Dirty Table of Contents with jQuery (ToC) by Matthew Elsom (@matthewelsom) on CodePen.