Created
June 27, 2012 01:31
-
-
Save ukyo/3000691 to your computer and use it in GitHub Desktop.
toc tree for gist
This file contains hidden or 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
(function(l, l2, s) { | |
l2 = l2 || 6; | |
NodeList.prototype.forEach = [].forEach; | |
NodeList.prototype.slice = [].slice; | |
var toc = document.createElement('div'); | |
var headerLevel = l || 2; | |
var tocStyle = s || 'ul'; | |
var headers = document | |
.querySelector('article') | |
.querySelectorAll('h1 h2 h3 h4 h5 h6'.split(' ').slice(headerLevel - 1).join()) | |
function buildList(header) { | |
var li = document.createElement('li'); | |
var a = document.createElement('a'); | |
var a_ = header.querySelector('a'); | |
a.href = a_.href; | |
a.innerHTML = header.innerText; | |
li.appendChild(a); | |
return li; | |
} | |
(function buildTocTree(tree, headers, level) { | |
var i, m, | |
indices = [], | |
hx = 'H' + level, | |
n = headers.length, | |
ul = document.createElement(tocStyle); | |
if(!n || level > l2) return; | |
tree.appendChild(ul); | |
function set(start, end) { | |
var li = buildList(headers[start]); | |
ul.appendChild(li); | |
buildTocTree(li, headers.slice(start + 1, end), level + 1); | |
} | |
for(i = 0; i < n; ++i) if(headers[i].tagName === hx) indices.push(i); | |
for(i = 0, m = indices.length - 1; i < m; ++i) set(indices[i], indices[i + 1]); | |
if(indices.length) set(indices[m], n); | |
})(toc, headers, headerLevel); | |
console.log(toc.innerHTML); | |
})(2, 6, 'ul'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment