Skip to content

Instantly share code, notes, and snippets.

@Marco3jp Marco3jp/app.js
Created Nov 2, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

najimammeri-veonum commented Dec 20, 2018

Thanks!

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.