Skip to content

Instantly share code, notes, and snippets.

@Marco3jp
Created November 2, 2018 17:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marco3jp/82aa4475ade5d5513cd19c42715a02d8 to your computer and use it in GitHub Desktop.
Save Marco3jp/82aa4475ade5d5513cd19c42715a02d8 to your computer and use it in GitHub Desktop.
Insert ToC in TypeScript Handbook.
// ==UserScript==
// @name PlusToC
// @namespace https://marco.plus
// @version 0.1
// @description Insert ToC in TypeScript Handbook.
// @author Marco
// @match https://www.typescriptlang.org/docs/handbook/*
// @grant none
// ==/UserScript==
(function () {
'use strict';
let headingElements = document.querySelectorAll(".post-content h1, .post-content h2");
let tocMother = document.createElement("div");
let toc = document.createElement("ol");
let h2After = false;
for (let i = 0; i < headingElements.length; i++) {
if (headingElements[i].nodeName === "H1") {
let li = document.createElement("li");
let a = document.createElement("a");
a.setAttribute('href', `#${headingElements[i].id}`);
a.insertAdjacentText('afterbegin', headingElements[i].textContent);
li.appendChild(a);
toc.appendChild(li);
h2After = false;
} else if (h2After) {
let subList = toc.lastChild.lastChild;
let li = document.createElement("li");
let a = document.createElement("a");
a.setAttribute('href', `#${headingElements[i].id}`);
a.insertAdjacentText('afterbegin', headingElements[i].textContent);
li.appendChild(a);
subList.appendChild(li);
} else {
let h1 = toc.lastChild;
let ol = document.createElement("ol");
let childLi = document.createElement("li");
let a = document.createElement("a");
a.setAttribute('href', `#${headingElements[i].id}`);
a.insertAdjacentText('afterbegin', headingElements[i].textContent);
childLi.appendChild(a);
ol.appendChild(childLi);
h1.appendChild(ol);
h2After = true;
}
}
tocMother.appendChild(toc);
tocMother.style.marginTop = "45px";
tocMother.style.marginBottom = "-35px";
let postHeader = document.querySelector(".post-header");
postHeader.insertAdjacentElement('afterend', tocMother);
})();
@najimammeri-veonum
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment