Table of Content List Automaticly reading h2 h3 h4 ..etc

<span class="toc-label">Table of Contents: </span>
<span class="toggle-t-button">[<button id="toggle-toc">Show</button>]</span>
<div id="table-of-contents" style="display: none;"></div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    // Get all H2 elements on the page
    var headings = document.querySelectorAll("h2");
    if (headings.length === 0) return;

    var tocContainer = document.getElementById("table-of-contents");
    var tocList = document.createElement("ul");

    headings.forEach(function (heading, index) {
        var anchorId = "toc-heading-" + index;
        heading.setAttribute("id", anchorId);

        var listItem = document.createElement("li");
        var link = document.createElement("a");
        link.setAttribute("href", "#" + anchorId);
        link.textContent = heading.textContent;

        listItem.appendChild(link);
        tocList.appendChild(listItem);
    });

    tocContainer.appendChild(tocList);

    // Toggle button functionality
    var toggleButton = document.getElementById("toggle-toc");
    toggleButton.addEventListener("click", function () {
        if (tocContainer.style.display === "none") {
            tocContainer.style.display = "block";
            toggleButton.textContent = "Hide";
        } else {
            tocContainer.style.display = "none";
            toggleButton.textContent = "Show";
        }
    });
});
</script>

Upcoming Course

I am planning a professional WordPress and Bricks Builder course. If you are Interested register to this newsletter.