Table of Contents Tag

JavaScript Web Component
HTML / JS
GitHub Gist

What It Is

A tag which will display an embedded table of contents based on HTML header tags

Status

Last Reviewed:

Used in many places right now on this site.

Details

A web component that will generate a dynamic table of contents based on the heading tags in the page on which it’s embedded.

Here’s an example from the page you’re looking at right now (view source to see the code – it’s a web component, so everything is done in the browser):

On this page…

If you inspect the headers, you’ll see that an ID attribute has been dynamically added to each one.

The code below will form a menu of links to bookmarks based on the H2 and H3 tags in an element with the class of article. This menu will be under the contents of the header element.

<table-of-contents source=".article" selector="h2,h3">
  <header><em>This is the table of contents...</em></header>
</table-of-contents>

If no source is provided, it will search the entire body element.

If no selector is provided, it will search for H2 tags only. The selector can be any CSS selector (it just executes a querySelectorAll using that as an argument).

The entries in the TOC will be appended after the header element (if provided).

The links will have CSS class names based on their elements, so they can be indented differently.

Each entry in the TOC will be the text of the corresponding heading, but you can provide alternate text as an attribute, as shown below.

<h2 data-toc-title="The TOC Heading">This is a simple heading</h2>