Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{
let root = document.querySelector(".toc");
let h2s = document.querySelectorAll("h2");
function getNext(el, until, filter) {
let elements = [];
let elm = el.nextElementSibling;
while (elm) {
if (elm.matches(until)) break;
if (!elm.matches(filter)) {
elm = elm.nextElementSibling;
continue;
}
elements.push(elm);
elm = elm.nextElementSibling;
}
return elements;
}
function makeLI(element) {
element.id = element.innerText.replace(/\s+/g, "-");
let li = document.createElement("li"),
a = document.createElement("a");
a.setAttribute("href", "#" + element.innerText.replace(/\s+/g, "-"));
a.innerText = element.innerText;
li.appendChild(a);
return li;
}
let heading = document.createElement("h3");
let headingText = document.createTextNode("Table Of Contents");
heading.appendChild(headingText);
heading.className = "heading";
root.appendChild(heading);
let ul = document.createElement("ul");
for (let i = 0; i < h2s.length; i++) {
let h3s = getNext(h2s[i], "h2", "h3");
this.ul = ul.appendChild(makeLI(h2s[i]));
this.ul.className = "parentLI";
if (h3s.length > 0) {
for (let i = 0; i < h3s.length; i++) {
this.ul.appendChild(makeLI(h3s[i]));
}
}
root.appendChild(ul);
}
const style = document.createElement("style");
const styles = `
.heading {
margin: 0;
padding: 10px
}
.toc{
border: 1px solid #ccc;
width: 220px;
height: 160px
}
.toc ul {
padding-left: 30px;
margin: 0
}
.parentLI li{
margin-left : 20px;
list-style: circle
}
`;
style.innerHTML = styles;
document.querySelector("body").appendChild(style);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.