Last active
December 28, 2015 09:48
-
-
Save daimatz/7481350 to your computer and use it in GitHub Desktop.
GitHub Wiki TOC JS
This file contains hidden or 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 GitHub Wiki TOC | |
// @namespace http://www.daimatz.net/ | |
// @version 0.11 | |
// @description Add TOC to GitHub Wiki Page | |
// @include https://github.com/*/*/wiki/* | |
// @license MIT License(http://en.wikipedia.org/wiki/MIT_License) | |
// ==/UserScript== | |
(function() { | |
var toc = document.createElement('ul'); | |
toc.setAttribute('style', 'margin-bottom: 20px !important'); | |
var heads = document.querySelectorAll('.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown h4, .markdown h5, .markdown h6'); | |
for (var i = 0; i < heads.length; ++i) { | |
var space = heads[i].tagName.substring(1); | |
var childs = heads[i].childNodes | |
var text = childs[childs.length-1].nodeValue.trim(); | |
var id = text.replace(/\s+/g, '-'); | |
heads[i].id = id; | |
var li = document.createElement('li'); | |
li.setAttribute('style', 'margin-left:' + space + 'em;'); | |
var a = document.createElement('a'); | |
a.setAttribute('href', '#' + id); | |
a.innerHTML = text; | |
li.appendChild(a); | |
toc.appendChild(li); | |
} | |
var body = document.querySelector('.markdown-body'); | |
var hr = document.createElement('hr'); | |
var title = document.createElement('h2'); | |
title.innerHTML = 'Table of Contents'; | |
body.insertBefore(hr, body.firstChild); | |
body.insertBefore(toc, body.firstChild); | |
body.insertBefore(title, body.firstChild); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment