For my posts on dev.to I always want to have a Table of Contents. Until now I did that manually which was a lot of work. So I created a small JS snippet that you can use as bookmarklet.
A bookmarklet looks like a bookmark in your browser. But when you click it, a JS snippet runs on the current page.
Here's the source code. It goes through all h2 and h3 of the article, creates internal links, and concatenates them as markdown. Ready to copy & paste to your dev.to post.
(() => {
let toc = "";
let numH2 = 1;
let numH3 = 1;
document.querySelectorAll("article h2,article h3").forEach(element => {
const a = element.firstElementChild;
if (a?.nodeName === "A") {
const text = (element.lastChild?.nodeValue || "").replaceAll("\n", "").trim();
if (element.nodeName === "H2") {
toc += `${numH2}. [${text}](${a.hash})\n`;
numH2 += 1;
numH3 = 1;
} else if (element.nodeName === "H3") {
toc += ` ${numH3}. [${text}](${a.hash})\n`;
numH3 += 1;
}
}
});
console.log("## Table Of Contents\n\n" + toc);
})()
How to create a bookmarklet? Create a new bookmark in your browser. In place of the URL you type javascript:
followed by your code.
Here the minified JS snippet from above for your bookmark.
javascript:(()=>{let toc="";let numH2=1;let numH3=1;document.querySelectorAll("article h2,article h3").forEach(element=>{const a=element.firstElementChild;if(a?.nodeName==="A"){const text=(element.lastChild?.nodeValue||"").replaceAll("\n","").trim();if(element.nodeName==="H2"){toc+=`${numH2}. [${text}](${a.hash})\n`;numH2+=1;numH3=1}else if(element.nodeName==="H3"){toc+=` ${numH3}. [${text}](${a.hash})\n`;numH3+=1}}});console.log("##%20Table%20Of%20Contents\n\n"+toc)})()
Top comments (4)
That’s interesting. Are you using the table of contents on a blog or just for having it? Could see lots of benefits to this for longer articles or multi subject articles.
I use this in most of my post here (for example this one.
On my blog I have a custom ToC that's generated automatically and looks different on desktop and mobile. Here's the same article on my blog.
Nice. I’ll have to check this out for future articles I write if they are longer.
Nice one! I also created a tool for it: derlin.github.io/bitdowntoc/ (choose the
dev.to
preset ;)) but it requires more than one click. It does, however, let you choose where the TOC is located and some other cool stuff (limit headings levels, etc).See:
Finally a clean and easy way to add Table of Contents to dev.to articles 🤩
Lucy Linder ・ Jan 2 ・ 4 min read