Created
January 22, 2017 10:57
-
-
Save simov/4b4cfefa1bf0e5f0c359f7635326fa06 to your computer and use it in GitHub Desktop.
Generate Table of Contents (TOC) from rendered HTML document's header tags
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.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