<simple-toc>
Create a basic table of contents from the page headings.
Usage
Include a <simple-toc>
element in your HTML. It will automatically generate a list of anchor links to all of the h2
heading elements that have IDs.
<simple-toc></simple-toc>
If you include a [heading]
attribute, its value will be used as the first item in the list.
<simple-toc heading="On this page..."></simple-toc>
The Web Component
customElements.define('simple-toc', class extends HTMLElement {
/**
* Instantiate the Web Component
*/
constructor () {
// Get parent class properties
super();
// Generate HTML
let heading = this.getAttribute('heading');
let navList = Array.from(document.querySelectorAll('h2')).map(function (heading) {
if (!heading.id) return '';
return `<li><a href="#${heading.id}">${heading.textContent}</a></li>`;
}).join('');
// Make sure a navList exists
if (navList.length < 1) return;
// Render the HTML
this.innerHTML = `<ul>${heading ? `<li><strong>${heading}</strong></li>` : ''}${navList}</ul>`;
}
});