forked from ashok-khanna/pdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toc.js
62 lines (46 loc) · 1.91 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function createToc(config){
const content = config.content;
const tocElement = config.tocElement;
const titleElements = config.titleElements;
let tocElementDiv = content.querySelector(tocElement);
let tocUl = document.createElement("ul");
tocUl.id = "list-toc-generated";
tocElementDiv.appendChild(tocUl);
// add class to all title elements
let tocElementNbr = 0;
for(var i= 0; i < titleElements.length; i++){
let titleHierarchy = i + 1;
let titleElement = content.querySelectorAll(titleElements[i]);
titleElement.forEach(function(element) {
// add classes to the element
element.classList.add("title-element");
element.setAttribute("data-title-level", titleHierarchy);
// add id if doesn't exist
tocElementNbr++;
idElement = element.id;
if(idElement == ''){
element.id = 'title-element-' + tocElementNbr;
}
let newIdElement = element.id;
});
}
// create toc list
let tocElements = content.querySelectorAll(".title-element");
for(var i= 0; i < tocElements.length; i++){
let tocElement = tocElements[i];
let tocNewLi = document.createElement("li");
// Add class for the hierarcy of toc
tocNewLi.classList.add("toc-element");
tocNewLi.classList.add("toc-element-level-" + tocElement.dataset.titleLevel);
// Keep class of title elements
let classTocElement = tocElement.classList;
for(var n= 0; n < classTocElement.length; n++){
if(classTocElement[n] != "title-element"){
tocNewLi.classList.add(classTocElement[n]);
}
}
// Create the element
tocNewLi.innerHTML = '<a href="#' + tocElement.id + '">' + tocElement.innerHTML + '</a>';
tocUl.appendChild(tocNewLi);
}
}