Create Table of Contents with JavaScript and Browser DevTools
When creating an article, such as a blog post for freeCodeCamp, Hashnode, Medium, or DEV.to, you can help guide the reader by creating a Table of Contents (ToC). In this article, we will explain how to create one with the help of JavaScript and browser DevTools.
Browser Dev Tools
Dev Tools is an extension to the browser that can allow you to inspect and manipulate the DOM (Document Object Model), which is a representation of the HTML the browser keeps in memory in the form of a tree. It also gives access to the JavaScript console, where you can write short code snippets to test something.
JavaScript Console
We will need to have access to the JavaScript console. To open the console in Google Chrome, you can use F12, right-click on the page and select Inspect from the context menu, or use the shortcut CTRL+SHIFT+C (Windows, Linux) or CMD+OPTION+C (Mac).
Understanding the DOM Structure
The first step to create a ToC is to inspect the DOM and find the headers. They are usually H1…H6 tags. H1 is often the title of the page.
Now with DevTools, we can write code that will find every header: document.querySelectorAll('h2[id], h3[id], main h4[id]');
How to Create the ToC in Markdown
A lot of blogging platforms support Markdown, so it’ll be the first thing we’ll create.
First, we’ll convert the Node list to an array. We can use the spread operator: [...document.querySelectorAll('main h2[id], main h3[id], main h4[id]')];
Then we can map over the array and create the Markdown links that point to the given header.
How to Create an HTML ToC
If your platform doesn’t support Markdown (like Medium), you can create HTML, preview that HTML, and copy the output to the clipboard.
Conclusion
In conclusion, creating a Table of Contents with JavaScript and browser DevTools is a simple process that can help guide your readers. By following these steps, you can create a ToC that will improve the readability of your article.
Call to action: Try creating a Table of Contents for your next article using JavaScript and browser DevTools.
Frequently Asked Questions
- Q: What is a Table of Contents?
- A: A Table of Contents is a list of links that point to the different sections of an article.
- Q: How do I create a Table of Contents with JavaScript and browser DevTools?
- A: You can create a Table of Contents by using the JavaScript console to find the headers in your article and then mapping over the array to create Markdown links.
- Q: Can I use this method on any platform?
- A: Yes, you can use this method on any platform that supports Markdown or HTML.
- Q: Do I need to have any prior knowledge of JavaScript or HTML to use this method?
- A: No, you don’t need to have any prior knowledge of JavaScript or HTML to use this method.
- Q: Is this method free?
- A: Yes, this method is free and can be used on any platform that supports Markdown or HTML.








