DEV Community

Cover image for How to create a table of content for a Dev.to post
Kevin Bravo
Kevin Bravo

Posted on • Updated on

How to create a table of content for a Dev.to post

Table of Contents

 1. Basic about markdowns
       1.1. Headers
       1.2. Links

 2. Basic Table of content (manually)
 4. Create your Table of content automatically.


In this article I'm going to show you how you can create a table of content (ToC) for your dev.to post automatically.

This is based on this previous post of @goldenxp.

I'm going to explain a little bit how markdowns work, if you already know that and only want the code to make your ToC go to this section.

Basic about markdowns

Headers

So, when you want to write headers in markdown, you have to do something like this.

## my H2 header
### my H3 header
#### my H4 header
##### my H5 header
###### my H6 header
Enter fullscreen mode Exit fullscreen mode

And it looks something like this:

Screenshot from the dev.to preview format and the console

Screenshot from the dev.to preview format and the console with the div object in which all the elements of an article are contained.

Note: you can have another H1 header, but it‘s not recommended, you must only have one H1 header for the title, this helps the semantics of the site, so You should use only from H2 to H6 headers in the content of your article.

Links

Links in markdown format looks like this

[The hypertext](https//:mylink.com)
Enter fullscreen mode Exit fullscreen mode

You must use the syntax []() to indicate that this element is a link.

In your render document you will have something like this.

Link to my twitter account

Of course, those links are links would get you to another page, so if we want to write links that points to a specific position in our text, like in this github example:

Screnshot of a url example

The url from above:

https://github.com/mustafinho/mustafinho/blob/main/AMA.md#octocat-computer-talk-techy-to-me

It points to the same page but to a different point in the article, and you can identify that by locating the “#” symbol after the original url of the page where you are.

Basic Table of content (manually)

We can make our ToC by using the different ‘H’ tags (H2,H3,H4,...) and using the “#” so, we can redirect the user to a subsection of the article.

Opening the console in the preview mode of the dev.to text editor

image of the container in dev.to

We can see how the links look within the article. In the href section notice how the links are written.: “#” followed by the name of the section with the hyphens

So, we can point to those headers and travel through the article directly to them

We just need have to write:

[click here to be redirected to my h4 section](#my-h4-header)

And you will get:

Screnshot of the rendered markdown

Notice the redirection link below

So, for make our table of content, we can simply do something like this

Table of Contents

  1. to my h2 header

   a. to my h3 header

     - to my h4 header

screnshot of the rendered markdown

And that's it, we have our table of content.

BUT, if you have a really big document, this could be kind of annoying doing all the h2,h3…. Tags that may have, so there has to be a way in which we can do this automatically right?

Meme

Right?

Meme

Yes, but it is not an official solution, I just write a javascript code that can be executed in the console that makes it automatically for you.

Create your Table of content automatically.

I just grab all the children tags that the container of the article has, and make a script so, if they are header tags, it will format and indent them, putting a number or a letter depending on the tag.

We can see that the div in where all the content for the article is contained (preview mode in the dev.to text editor with the console open)

Screnshot of the container text

Console in the text editor using the preview mode

That's what this javascript code does. 👇

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

const orderedNumbers = {}
let markDownIndentation = "      "

let actualIndex
let actualSubIndex = 0;
let actualLetterIndex = 0
const letters = ["a", "b", "c", "d", "f", "g", "f", "h", "i"];
const usedLetters = [];

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

    if (tag === "H2") {
      outputMarkDown += markDownIndentation.repeat(indent)
    }
    else {
      outputMarkDown += "\n" + markDownIndentation.repeat(indent);
    }

    switch (tag) {
      case "H2":
        if (!orderedNumbers[indent]) actualIndex = orderedNumbers[indent] = 1
        actualIndex = orderedNumbers[indent]++
        outputMarkDown += " " + actualIndex + ". ";
        break
      case "H3":
        (actualSubIndex === 0) ? actualSubIndex = 1 : actualSubIndex++
        outputMarkDown += ` ${actualIndex}.${actualSubIndex}. `;
        break
      case "H4":
        usedLetters.push(letters[actualLetterIndex])
        letters.pop(actualLetterIndex)
        outputMarkDown += ` ${usedLetters[actualLetterIndex]}. `;
        actualLetterIndex++
        break
      case "H5":
        outputMarkDown += "- ";
        break
    }
    if (tag === "H6") {
      outputMarkDown += "[*" + item.textContent.trim() + "*](" + link + ")\n";
    }
    else {
      outputMarkDown += "[" + item.textContent.trim() + "](" + link + ")\n";
    }
  }
}
console.log(outputMarkDown);
Enter fullscreen mode Exit fullscreen mode

You just need to:

  1. Have an amazing article with subsections (H2,H3,H4..)
  2. Copy the above code
  3. Go to the text editor of dev.to
  4. Click in the preview mode Screnshot of the dev.to editor in preview mode
  5. Open the console
  6. Paste the code in the console.
  7. Press enter

Ta da!, you have your table of content completely formatted for your amazing dev.to post.

Now, you just have to copy that output and paste it in your text.

I'm not going to explain in dev what this javascript code does, because is out of the purposes of this article, but I will explained in the github repo of the script

Again, thanks to this post for the inspiration.

DISCLAIMER: take into account that the configuration for the script may change with the time as the team of dev to change the layout of it's page.


That's all folks.

I hope this article was helpful for you.

If you have any comment or suggestions, please leave it in the comments section.

You can follow me on twitter @_bravok and DM me, I’m always happy to talk and get to know more people in this amazing community.

If you publish your article and use this method to generate your table of content, share your article on twitter and tag me (@kevbto). Let me see your incredible creation, I'll retweet

Top comments (10)

Collapse
 
nathlowe profile image
NathLowe

Thank you for the amazing article. I was lazy and directly dived into the article without even looking at your TOC. Consequence, I only read the part where you explain how to create it manually😅 and ended up wasting more time. I should have read the whole article or at least the TOC 😂.

For those who had trouble like me, just go to this section:
dev.to/bravok/how-to-create-a-tabl...

Collapse
 
j471n profile image
Jatin Sharma

Nice work. Keep it up.

Collapse
 
jasurkurbanov profile image
Jasur Kurbanov

Thank you for tutorial! It helped for me. Check out my table of content

Collapse
 
bravok profile image
Kevin Bravo

Thank you for the comment Jasur, I'll really appreciate it 💚 Hope the info was helpful for you!

Collapse
 
devyoma profile image
Emore Ogheneyoma Lawrence

This just helped me create my ToC,
Thank you

Collapse
 
vattybear profile image
Ganesh Swaminathan

Neat hack - thanks!!

Collapse
 
bravok profile image
Kevin Bravo

Thank you for your comment Ganesh!. Hope the article was helpful for you!🚀

Collapse
 
derlin profile image
Lucy Linder

Nice job!

However, if you are not comfortable copy-pasting javascript around and want an easy+re-doable way of adding TOC to your article, I just released BitDownToc with dev.to support: derlin.github.io/bitdowntoc/ (choose the dev.to preset ;))

To know more, see my article:

Collapse
 
nelsonfigueroa profile image
Nelson Figueroa

This just helped me out right now. Thanks!

Collapse
 
danielrendox profile image
Daniel Rendox

Thanks 😊