Skip to content

Instantly share code, notes, and snippets.

@piroor
Last active September 22, 2021 07:46
Show Gist options
  • Save piroor/7a1af02f2afae6ed60ade3fe2c09c1ad to your computer and use it in GitHub Desktop.
Save piroor/7a1af02f2afae6ed60ade3fe2c09c1ad to your computer and use it in GitHub Desktop.
Generate Table of Contents Markdown code from HTML page
// Run this in the console of the web browser
(function generateToC() {
const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
if (headings.length == 0)
return;
let minLevel = 6;
for (let heading of headings) {
let headingLevel = parseInt(heading.localName.charAt(1));
if (headingLevel < minLevel)
minLevel = headingLevel;
}
const toc = [];
for (let heading of headings) {
let anchor = heading.querySelector('a[href]');
let indent = '';
let headingLevel = parseInt(heading.localName.charAt(1));
for (let level = headingLevel - minLevel; level > 0; level--) {
indent += ' ';
}
toc.push(`${indent}* [${heading.textContent.trim().replace(/\s\s+/g, ' ')}](${anchor ? anchor.href : '#'+heading.id})`);
}
console.log(toc.join('\n'));
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment