Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active April 2, 2020 13:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieMason/c43e7ee1d078fc63e7c0f15746845c2e to your computer and use it in GitHub Desktop.
Save JamieMason/c43e7ee1d078fc63e7c0f15746845c2e to your computer and use it in GitHub Desktop.
Quick way to generate a table of contents from a GitHub README

Quick way to generate a table of contents from a GitHub README

Visit the README.md on GitHub.

Paste this into the console in Google Chrome.

[].map
  .call(document.querySelectorAll('.anchor'), el => 
    `* [${el.parentNode.innerText}](${el.getAttribute('href')})`
  )
  .join('\n');

The output if run on the lodash README should look something like this;

"* [lodash v4.14.0](#lodash-v4140)
* [Download](#download)
* [Why Lodash?](#why-lodash)
* [Module Formats](#module-formats)"

Include indentation

The following version is longer, but will indent the items according to the headers;

[].map
  .call(document.querySelectorAll('.anchor'), function(el) {
    var indents = '  '.repeat(parseFloat(el.parentNode.nodeName.charAt(1)) - 1);
    var label = el.parentNode.innerText;
    var link = el.getAttribute('href');
    return `${indents}* [${label}](${link})`
  })
  .join('\n');

The output if run on the lodash README should look something like this;

"* [lodash v4.15.0](#lodash-v4150)
  * [Download](#download)
  * [Why Lodash?](#why-lodash)
  * [Module Formats](#module-formats)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment