Juri Strumpflohner

RSS
all notes 🌱 seedling · Updated

Generate a TOC for Dev.to Posts

Author profile pic
Juri Strumpflohner

If you want to include a table of content in your dev.to posts there’s no easy integrated way atm unfortunately (if there is, plz ping me and let me know).

I use a script to generate one. Basically:

  • open your browser’s devtools
  • paste in the script below
  • you have the markdown printed out and copied to your clipboard (might only work in Chrome)

Then just go and paste it into your article wherever you like and you’re done :).

The Script

const elements = document.getElementsByClassName("crayons-article__body text-styles")
let outputMarkDown = "## Table of Contents\n";

let markDownIndentation = "  "; // Adjusted indentation for markdown

for (let item of elements[0].children) {
  const tag = item.nodeName;

  if (tag === "H2" || tag === "H3" || tag === "H4" || tag === "H5" || tag === "H6") {
    const link = "#" + item.firstElementChild.name;
    const indent = tag.slice(-1) - 2;
    const indentString = markDownIndentation.repeat(indent);

    // Using bullet points for all headings
    outputMarkDown += indentString + "- [" + item.textContent.trim() + "](" + link + ")\n";
  }
}

copy(outputMarkDown);
console.log(outputMarkDown);