Created
November 2, 2018 17:15
-
-
Save Marco3jp/82aa4475ade5d5513cd19c42715a02d8 to your computer and use it in GitHub Desktop.
Insert ToC in TypeScript Handbook.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!