Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Forked from ukyo/gist-toc.js
Last active March 7, 2019 21:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyecatchup/5188107e5fbc9c8d0fa3 to your computer and use it in GitHub Desktop.
Save eyecatchup/5188107e5fbc9c8d0fa3 to your computer and use it in GitHub Desktop.
toc tree for gist
(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');
# 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