-
Notifications
You must be signed in to change notification settings - Fork 0
/
toc.js
30 lines (27 loc) · 800 Bytes
/
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
(() => {
const toc = document.getElementById('toc');
const headings = [...document.querySelectorAll('h2,h3')]
.slice(1);
let lastLi;
for (let i = 0; i < headings.length; i++) {
const hn = headings[i];
const anchor = hn.innerText.toLowerCase().replace(/[^a-z]+/g, '-');
const li = document.createElement('li');
const a = document.createElement('a');
li.appendChild(a);
a.innerText = hn.innerText;
hn.setAttribute('id', anchor);
a.setAttribute('href', `#${anchor}`);
if (hn.nodeName === 'H3') {
let ul = lastLi.querySelector('ul');
if (!ul) {
ul = document.createElement('ul');
lastLi.appendChild(ul);
}
ul.appendChild(li);
} else {
lastLi = li;
toc.appendChild(li);
}
}
})();