Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active April 2, 2020 13:27
Show Gist options
  • Select an option

  • Save JamieMason/c43e7ee1d078fc63e7c0f15746845c2e to your computer and use it in GitHub Desktop.

Select an option

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.nextSibling.nodeValue}](${el.getAttribute('href')})`
  )
  .join('\n');

The output should look something like this;

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

The above example was run at https://github.com/lodash/lodash.

EDIT

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

[].map
  .call(document.querySelectorAll('.anchor'), function(el) {
    var indents = '  '.repeat(parseFloat(el.parentNode.nodeName.charAt(1)) - 1);
    var label = el.nextSibling.nodeValue;
    var link = el.getAttribute('href');
    return `${indents}* [${label}](${link})`
  })
  .join('\n');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment