Making of a table of contents script

I wanted to use an automatic table of content script to generate a TOC if necessary for this blog. I picked a script written by Ates Goral on stackoverflow: stackoverflow.com/a/187946.

When I was writing the Localization Routes post I noticed that some of the table content links weren't working properly. The error was that some headings were called ____________Id____________. So instead of trying to understand why the table of content script wasn't working I decided to write my own for fun.

I made the automatic table of content generation using typescript and the code is in the snippet below. What the code does is look for a #toc and #content element. Then it finds all the h1 to h6 elements inside the #content element. The cool part is that querySelectorAll() returns them in order of appearance so there's no need to sort them. So it's just a matter of iterating over each heading element and increase/decrease the level of the ToC.
The code can be found on github or in the snippet below: here.

Now what I learned was that Ates Goral's script worked just fine. It however was my heading tags that had tabs and many spaces in them which generated the ____________Id____________. Which is the reason the trim() function is used.
So the point of this whole post is that here is another ToC auto generator but now written in typescript!

1 comment:

  1. Hey there's support for fenced code blocks!
    `console.log("and as always ...");`

    1. // multi-line!
    2. console.log("... stay nuusome!");
    ReplyDelete