o2m3ba
Last Updated: February 25, 2016
·
232
· douglasduteil

Extract the table-of-contents of a rendered markdown from the console

Extract the table-of-contents of a rendered markdown from the console

Generate a markdown TOC (table of contents) with your dev console.

Picture

I was so lazy of writing the actual TOC of a README that I code a console script to do it...

THE GOAL

Extract from the rendered markdown :

Picture

# A-H1

Lorem ipsum dolor sit amet...

## A-H2

Lorem ipsum dolor sit amet...

## B-H2

Lorem ipsum dolor sit amet...

### A-H3

Lorem ipsum dolor sit amet...

## C-H2

Lorem ipsum dolor sit amet...

### A-H3

Lorem ipsum dolor sit amet...

### B-H3

Lorem ipsum dolor sit amet...

# B-H1

Lorem ipsum dolor sit amet...

## A-H2

Lorem ipsum dolor sit amet...

## B-H2

Lorem ipsum dolor sit amet...

## C-H2

Lorem ipsum dolor sit amet...

# C-H1

Lorem ipsum dolor sit amet...

### A-H3

Lorem ipsum dolor sit amet...

The TOC like :

 - [A-H1](#a-h1)
  - [A-H2](#a-h2)
  - [B-H2](#b-h2)
    - [A-H3](#a-h3)
  - [C-H2](#c-h2)
    - [A-H3](#a-h3-1)
    - [B-H3](#b-h3)
- [B-H1](#b-h1)
  - [A-H2](#a-h2-1)
  - [B-H2](#b-h2-1)
  - [C-H2](#c-h2-1)
- [C-H1](#c-h1)
    - [A-H3](#a-h3-2)

THE Code

SRC

// By default I extract H* tags
// from the first `.markdown-body` element (for GitHub *.md for example)
console.clear();
(function mdToxExtract(targetTagName, summary, e){

  if (!e) {
    console.log(summary);
    return;
  }

  if (targetTagName.test(e.tagName)){
    var level = e.tagName.match(targetTagName)[1];
    var indentation = Array.apply(null, {length: ((level - 1) * 2) + 1}).join(' ');
    summary += [
      indentation,
      '- [', e.innerText, ']',
      '(', e.children[0].getAttribute('href'), ')', 
      '\n'
    ].join('');
  }

  setTimeout.call(null, mdToxExtract.bind(null, targetTagName, summary, e.nextElementSibling));

}.bind({}, /^H(\d+)/, ''))
(document.querySelector('.markdown-body').children[0])
;

Minified version :

console.clear();(function e(t,n,r){if(!r){console.log(n);return}if(t.test(r.tagName)){var i=r.tagName.match(t)[1];var s=Array.apply(null,{length:(i-1)*2+1}).join(" ");n+=[s,"- [",r.innerText,"]","(",r.children[0].getAttribute("href"),")","\n"].join("")}setTimeout.call(null,e.bind(null,t,n,r.nextElementSibling))}).bind({},/^H(\d+)/,"")(document.querySelector(".markdown-body").children[0])

Note :

The exploration is made sibling element by sibling element. So you can trigger the extraction from wherever you want in the DOM. Just select the starting point and use $0 like :

console.clear();(function e(t,n,r){if(!r){console.log(n);return}if(t.test(r.tagName)){var i=r.tagName.match(t)[1];var s=Array.apply(null,{length:(i-1)*2+1}).join(" ");n+=[s,"- [",r.innerText,"]","(",r.children[0].getAttribute("href"),")","\n"].join("")}setTimeout.call(null,e.bind(null,t,n,r.nextElementSibling))}).bind({},/^H(\d+)/,"")($0)