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'));
@pflegende
Copy link

good idea!
alert(toc.join('\n'));
apears but the (perfect! and also complete, fine rendered) content is not touchable.
Other than in the time* bookmarklet (in the same environment, browser, OS etc) you couldnt copy the alert content.

For the moment the toc so is only a nice picture in a alert ...

Some solving suggestion?

:)

the time bookmarklet looks like:
javascript: alert(new Date().toLocaleString())

@pflegende
Copy link

seems it is a dependency of Number of lines > 1
or may be number of \n > 1

on your gist readme (above) it is fine
but not a toc, only a Headline because your gist has no h1... h5

So, the question is:

How to make a alert with number of includet \n > 1 touchable for clipboard?

With the time.bookmarklet I tried a direct "giv-to-clipboard"
but doesnt work ...

may be you find it with more luck

:)

@pflegende
Copy link

may be this will work:
(only the clipboard attached after your coding)
pflegende/agatab@391a923

thx for the great toc-generator
:)

@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