-
Notifications
You must be signed in to change notification settings - Fork 1
/
toc.js
43 lines (42 loc) · 1.23 KB
/
toc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* make a table of content
* @param {element} ins - the thing you want to outline
* @return {string} - a html string
* @example
* var a = document.getElementById('aReallyLongDoc')
* document.getElementById('aSmallOutline').innerHTML = toc(a)
*/
function toc(ins) {
var ell = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'];
var lst = ins.querySelectorAll(ell);
var html = '<ul>';
var IndentLevel = '';
lst.forEach((element) => {
var Indent = ell.indexOf(element.tagName);
var toIndent = Indent - IndentLevel;
while (toIndent != 0) {
if (toIndent > 0) {
html += '<ul>';
toIndent--;
IndentLevel++;
}
if (toIndent < 0) {
html += '</ul>';
toIndent++;
IndentLevel--;
}
}
html +=
'<li><a class="hyperlink text-muted" href="#' +
element.innerText
.toLowerCase()
.replace(/\s/g, '-')
.replace('/', '')
.replace(')', '') +
'">' +
element.innerText.replace('<', '').replace('>', '') +
'</li>';
});
html += '</ul>';
return html;
}