-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoc.js
More file actions
73 lines (72 loc) · 2.37 KB
/
toc.js
File metadata and controls
73 lines (72 loc) · 2.37 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function tocGetText(e) {
"use strict";
var text = "", x;
for (x = e.firstChild; x !== null; x = x.nextSibling) {
if (x.nodeType === x.TEXT_NODE) {
text += x.data;
} else if (x.nodeType === x.ELEMENT_NODE) {
text += tocGetText(x);
}
}
return text;
}
function tocMake() {
"use strict";
var menu = document.createElement("ol");
var children = document.body.childNodes;
var chapter;
var chapterId;
var submenu;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType == 1) {
switch(children[i].nodeName)
{
case "H1":
var content = tocGetText(children[i]);
chapterId = encodeURIComponent(content.toLowerCase()).replace(/%20/g,'.');
children[i].setAttribute("id", chapterId);
var link = document.createElement("a");
link.setAttribute("href", "#" + chapterId);
var language = children[i].getAttribute("lang")
if (language !== null && language !== undefined)
link.setAttribute("lang", language);
link.innerHTML = children[i].innerHTML;
chapter = document.createElement("li");
chapter.appendChild(link);
menu.appendChild(chapter);
submenu = null;
break;
case "H2":
var content = tocGetText(children[i]);
var id = chapterId + "_" + encodeURIComponent(content.toLowerCase()).replace(/%20/g,'.');
children[i].setAttribute("id", id);
var link = document.createElement("a");
link.setAttribute("href", "#" + id);
var language = children[i].getAttribute("lang")
if (language !== null && language !== undefined)
link.setAttribute("lang", language);
link.innerHTML = children[i].innerHTML;
var section = document.createElement("li");
section.appendChild(link);
if (submenu === null) {
submenu = document.createElement("ol");
chapter.appendChild(submenu);
}
submenu.appendChild(section);
break;
}
}
}
var nav = document.createElement("nav");
var title = document.createElement("h1");
title.appendChild(document.createTextNode(""));
nav.appendChild(title);
nav.appendChild(menu);
var header = document.getElementsByTagName("header")[0];
if (document.getElementById("abstract") != null) {
header.parentNode.insertBefore(nav, document.getElementById("abstract").nextSibling);
} else {
header.parentNode.insertBefore(nav, header.nextSibling);
}
}
window.onload = tocMake;