-
-
Save itobey/3be283a589dbd53151f9f9a2762c1601 to your computer and use it in GitHub Desktop.
Generate Table of Contents (TOC) for Dillinger Styled HTML export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// extract all headers | |
var headers = [] | |
function walk (nodes) { | |
nodes.forEach((node) => { | |
var sub = Array.from(node.childNodes) | |
if (sub.length) { | |
walk(sub) | |
} | |
if (/h[1-6]/i.test(node.tagName)) { | |
headers.push({ | |
id: node.getElementsByTagName("a")[0].getAttribute('id'), | |
level: parseInt(node.tagName.replace('H', '')), | |
title: node.innerText | |
}) | |
} | |
}) | |
} | |
walk(Array.from(document.body.childNodes)) | |
console.dir(headers) | |
// generate TOC | |
var link = (header) => | |
'<li><a href="#' + header.id + '">' + header.title + '</a></li>' | |
var html = '<ul>' | |
headers.forEach((header, index) => { | |
if (index) { | |
var prev = headers[index - 1] | |
} | |
if (!index || prev.level === header.level) { | |
html += link(header) | |
} | |
else if (prev.level > header.level) { | |
html += '</ul>' + link(header) | |
} | |
else if (prev.level < header.level) { | |
html += '<ul>' + link(header) | |
} | |
}) | |
html += '</ul>' | |
document.body.insertAdjacentHTML('afterbegin', html) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment