Skip to content

Instantly share code, notes, and snippets.

@daimatz
Last active December 28, 2015 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daimatz/7481350 to your computer and use it in GitHub Desktop.
Save daimatz/7481350 to your computer and use it in GitHub Desktop.
GitHub Wiki TOC JS
// ==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