Skip to main content Accessibility Feedback
Skip to Documentation Content

Table of Contents

Generate a list anchor links for the headings on the page.

Usage

Include the <kelp-toc> element in your HTML.

By default, it generates an unordered list (<ul>) of anchor links with the .list-inline class from the h2 headings on the page.

If a heading does not have an ID, the component dynamically creates one.

<kelp-toc></kelp-toc>

Nested Headings

For more complex tables of contents, add the [nested] attribute. The component will target heading levels h2 through h6, and nested smaller headings under their parent sections.

<kelp-toc nested></kelp-toc>

Options

Use custom attributes to configure component settings.

  • [nested] - If present, create a nested table of contents.
  • [level] - The heading level to target (default: h2, or h2, h3, h4, h5, h6 when [nested] is present).
  • [heading] - A label to use before the list items (default: none).
  • [heading-type] - The type of element to use for the heading (default: li inside list, or h2 with [nested]).
  • [target] - A selector string for the element to generate links for (default: document).
  • [list-class] - A list of classes to use on the list (default: list-inline).
  • [list-type] - The type of list element to use (ul or ol, default: ul).
<kelp-toc
	nested
	level="h3, h4"
	heading="On this page..."
	heading-type="h3"
	target="#content"
	list-class="list-unstyled"
	list-type="ol"
></kelp-toc>

Events

The <kelp-toc> element emits a kelp-toc:ready event once the table of contents has been rendered into the DOM.

document.addEventListener('kelp-toc:ready', (event) => {
	console.log('ready:', event.target);
});

Methods

While web components are self-instantiating, the <kelp-toc> element has a few methods you can manually run if needed.

  • .render() - Generate a new table of contents. Useful if you’ve dynamically changed the headers on the page.
  • .init() - Manually initialize the component, if it fails for some reason.
const toc = document.querySelector('kelp-toc');

// Render a fresh table of contents
toc.render();

// Manually initialize the component
toc.init();