Skip to content

Instantly share code, notes, and snippets.

@jurijsk
Created May 5, 2023 14:49
Show Gist options
  • Save jurijsk/9f94e4b7c3247d170708511f0a4702ac to your computer and use it in GitHub Desktop.
Save jurijsk/9f94e4b7c3247d170708511f0a4702ac to your computer and use it in GitHub Desktop.
const toc = document.getElementById('table-of-contents');
for (const x of document.querySelectorAll('h2, h3')) {
const id = x.innerText.replaceAll(/[^a-z0-9]/gi,'');
x.id = id;
const item = `<li><a href="#${id}">${x.innerText}</a></li>`;
switch (x.tagName.toLowerCase()) {
case "h2": toc.insertAdjacentHTML('beforeend', `${item}<ul></ul>`); break;
case "h3": [...toc.querySelectorAll('ul')]?.pop()?.insertAdjacentHTML('beforeend', item); break;
}
}
//from https://taylor.town/toc-snippet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment