Skip to content

Instantly share code, notes, and snippets.

@sillero
Last active April 26, 2024 22:43
Show Gist options
  • Save sillero/ba07348369b0d2354245 to your computer and use it in GitHub Desktop.
Save sillero/ba07348369b0d2354245 to your computer and use it in GitHub Desktop.
GitHub markdown TOC generator (bookmarklet)

#GitHub markdown TOC generator (bookmarklet) Drag THIS LINK to the your bookmarks

javascript:!function(e){var r=["###Table of contents"];[].map.call(e.querySelectorAll("h1, h2, h3, h4, h5, h6"),function(e){var t=[Array(parseInt(e.tagName[1])).join(" "),"- [",e.innerText,"](",e.querySelector("a").getAttribute("href"),")"];r.push(t.join(""))}),alert(r.join("\n"))}(document.querySelector(".markdown-body"))
(function(markdownBody){
var toc = ['###Table of contents'];
[].map.call(markdownBody.querySelectorAll('h1, h2, h3, h4, h5, h6'), function(node){
var str = [
Array(parseInt(node.tagName[1])).join(' '),
'- [',
node.innerText,
'](',
node.querySelector('a').getAttribute('href'),
')'
];
toc.push(str.join(''));
});
alert(toc.join('\n'));
})(document.querySelector('.markdown-body'));
@nummacway
Copy link

It didn't work for me, but the fix was easy:
On github.com, replace querySelector('a') with nextElementSibling.
On github.io, I don't know why it doesn't work. The solution is a bit different:

var str = [
      Array(parseInt(node.tagName[1])).join('    '),
      '- [',
      node.innerText,
      '](#',
      node.getAttribute('id'),
      ')'

Thanks for the bookmarklet.

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