How to create a table of content for a Dev.to post
Tags: beginners, tutorial, javascript, bloging
Published: 2022-03-02 07:05:19

## Table of Contents
&nbsp;1. [Basic about markdowns](#basic-about-markdowns)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1.1. [Headers](#headers)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1.2. [Links](#links)

&nbsp;2. [Basic Table of content (manually)](#basic-table-of-content-manually)
&nbsp;4. [Create your Table of content automatically.](#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.](#create-your-table-of-content-automatically)

## 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
```

And it looks something like this:

![Screenshot from the dev.to preview format and the console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oi1ues4hk2n83177r4gd.png) 

*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)
```
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](https://twitter.com/KevBto)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a7a4fqh2b5ei1f03nx4k.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x4e3tmrvguqqziq6c2t5.png)
 
*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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8xrw3h74x7sgye5b5oq.png) 

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](#my-h2-header)

&nbsp;&nbsp; a. [to my h3 header](#my-h3-header)

&nbsp;&nbsp;&nbsp;&nbsp; -  [to my h4 header](#my-h4-header)

![screnshot of the rendered markdown](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4nhoge4gc9e1zfkmrlsl.png) 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i2tdjmx5y6wbzzrzc6d.png) 

Right?

![Meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74vy9zzk7br7ds3p21fk.png) 

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fueorm14jzithtjvcs2p.png) 

_Console in the text editor using the preview mode_

That's what this javascript code does.  :point_down:

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

const orderedNumbers = {}
let markDownIndentation = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"

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 += "&nbsp;" + 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);
```





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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zberozxsov616sxsj5j.png) 
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](https://github.com/mustafinho/devto-table-content-creator)

Again, thanks to [this post](https://dev.to/goldenxp/adding-table-of-contents-to-dev-to-posts-1ba4) 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](https://twitter.com/_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