Create table of content dynamically using jQuery

Create table of content dynamically using jQuery

Creating a dynamic table of contents using jQuery involves scanning the content of a page, identifying headings, and then generating a list of links that correspond to those headings.

Here's an example of how you can achieve this:

HTML structure:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Table of Contents</title>
    <div id="table-of-contents"></div>
    <div id="content">
        <p>This is the introduction section.</p>
        <h2>Section 1</h2>
        <p>This is the content of section 1.</p>
        <h2>Section 2</h2>
        <p>This is the content of section 2.</p>
        <h3>Subsection 2.1</h3>
        <p>This is a subsection within section 2.</p>

    <script src=""></script>
    <script src="script.js"></script>

jQuery script

$(document).ready(function() {
var tocContainer = $("#table-of-contents");
var contentHeadings = $("#content").find("h1, h2, h3");

if (contentHeadings.length > 0) {
    tocContainer.append("<h2>Table of Contents</h2>");

    contentHeadings.each(function(index, heading) {
        var $heading = $(heading);
        var headingText = $heading.text();
        var headingLevel = parseInt(heading.tagName.substring(1));

        // Create a list item and link for the heading
        var listItem = $("<li>");
        var link = $("<a>").attr("href", "#" + $heading.attr("id")).text(headingText);

        // Indent based on heading level
        listItem.css("margin-left", (headingLevel - 1) * 15 + "px");

        // Add the list item to the table of contents

        // Add an ID to the heading for linking
        $heading.attr("id", "toc-" + index);


In this example, the jQuery script first identifies the headings within the #content section and then generates a table of contents by creating a list of links to those headings. Learn create table of content dynamically using jQuery

The level of indentation in the table of contents is based on the heading level. The headings are also given IDs for easy linking. Make sure you replace the content and table-of-contents IDs with your actual HTML structure.

Related posts

Write a comment