TOC
Table of contents:
<div class="tbl-container">
<div class="tbl">
<div id="table-of-contents"></div>
</div>
</div>
document.addEventListener("DOMContentLoaded", function () {
const content = document.querySelector(".blog-copy"); // Adjust selector to your blog content container
const toc = document.getElementById("table-of-contents");
const headings = content.querySelectorAll("h2, h3");
if (!headings.length) return;
const tocList = document.createElement("ul");
headings.forEach((heading, index) => {
if (!heading.id) {
heading.id = "section-" + index;
}
const link = document.createElement("a");
link.href = "#" + heading.id;
link.textContent = heading.textContent;
const listItem = document.createElement("li");
// Create a span wrapper so you can inject the icon
listItem.innerHTML = `${tocIcon} `;
listItem.appendChild(link);
// Indent h3
if (heading.tagName.toLowerCase() === "h3") {
listItem.style.marginLeft = "20px";
}
tocList.appendChild(listItem);
});
toc.innerHTML = "<h2>Table of Contents</h2>";
toc.appendChild(tocList);
});
.tbl-container {
background-color: #f5f5f5;
padding:2rem;
margin-bottom: 1rem;
width:80%;
.tbl{
li {
position: relative;
margin: 1rem 0;
@apply hover:text-secondary
}
a {
@apply text-primary;
&:hover {
@apply text-secondary;
}
}
}
}