-
-
Save eyecatchup/5188107e5fbc9c8d0fa3 to your computer and use it in GitHub Desktop.
toc tree for gist
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
(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'); |
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
# gist toc usage | |
In fact, you just need to add these two lines to your markdown documents to automatically get a _Table of Contents_ | |
``` | |
<div id="#gist-toc">toc</div> | |
<script src="https://gist.github.com/raw/5188107e5fbc9c8d0fa3/gist-toc.js"></script> | |
``` | |
<div id="#gist-toc">toc</div> | |
<script src="https://gist.github.com/raw/5188107e5fbc9c8d0fa3/gist-toc.js"></script> | |
## 1 | |
### 1.1 | |
### 1.2 | |
#### 1.2.1 | |
#### 1.2.2 | |
### 1.3 | |
#### 1.3.1 | |
#### 1.3.2 | |
## 2 | |
### 2.1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment