Adding a dynamic table of contents to your Webflow blog posts is a great way to improve the user experience and SEO of your site.
Many of the biggest blogs in the world, such as Hubspot use this tecnhnique to great effect to rank at the top of Google.
We're going to show you how to easily add a table of contents to your webflow CMS rich text field, exactly like the one below.
In this post we'll cover:
- Add JavaScript to Your Template Page
- Assign a class to your Rich Text field
- Structure your blog post with H3 headings
- How the code works
Step 1: Add JavaScript to Your Template Page
We're going to add some custom javascript that will find all the H3 headings in your rich text field and add an ID to them.
Add the following JavaScript code to the custom code section of your blog post template page (before the closing </body>
tag). This script will dynamically generate the TOC based on the H3 headings in your blog post.
As you are adding this to the template page, you will only need to do this once and it will apply to all blog posts you create in future.
1<script>
2
3// find all h3 headings inside the .rich-text field
4let sections = document.querySelectorAll(".rich-text > H3");
5
6// add an incrementing number to each heading as an #id
7sections.forEach((section, i) => {
8 sections[i].id = ${i+1};
9});
10
11</script>
12
Step 2: Give your Rich Text field a class
The code will look for all H3 elements inside a class of "rich-text".
So, for this to work give your Rich Text element a class of ".rich-text".
That's all the set up complete.
In the next step, you just need to write your blog posts with H3 headings for your sections and then add a table of contents as a list at the top of your post.
Step 3: Write your blog posts
When you are writing your blog post, simple structure your post with H3 headings that will represent the sections you want to link to.
Each H3 will get an ID, starting at #1 and incrementing sequentially for every heading.
Somewhere near the top of your post, create an unordered list with names of the headings you want to link to.
Give each heading a link with the number section you want to link to. Your first H3 will be #1, second #2 etc etc.
Review of how the code works
Conclusion
Dynamic table of contents are a great way to enhance your UX and improve the SEO of your Webflow posts.
We love small wins like this that compound to dramatically improve your search ranking over time. Yesterday we shared how to compress and covert all your Webflow CMS images to AVIF to improve your SEO so make sure you check that one out too.
Reach out to us on X if you have trouble getting this set up!
This script was originally written by @Sai_Abhijith