Skip to content

Instantly share code, notes, and snippets.

@Amitind
Last active January 6, 2026 15:16
Show Gist options
  • Select an option

  • Save Amitind/010614e9b3da8d486dbd31cfd77d69f0 to your computer and use it in GitHub Desktop.

Select an option

Save Amitind/010614e9b3da8d486dbd31cfd77d69f0 to your computer and use it in GitHub Desktop.
Table of Content using JavaScript
// source: https://projectcodeed.blogspot.com/2020/04/an-automatic-table-of-contents.html
// Get ToC div
toc = document.getElementById("ToC");
// clear toc div if not clear
toc.innerHTML = "";
//Add a header
tocHeader = document.createElement("h2");
tocHeader.innerText="Table of contents";
toc.appendChild(tocHeader);
// Create a list for the ToC entries change it to make orderlist or unordered list
tocList = document.createElement("ol");
// Get the h3 tags - ToC entries
headers = document.getElementsByTagName("h3");
// For each h3
for (i = 0; i < headers.length; i++){
// Create an id
name = "h"+i;
headers[i].id=name;
// a list item for the entry
tocListItem = document.createElement("li");
// a link for the h3
tocEntry = document.createElement("a");
tocEntry.setAttribute("href","#"+name);
tocEntry.innerText=headers[i].innerText;
tocListItem.appendChild(tocEntry);
tocList.appendChild(tocListItem);
}
toc.appendChild(tocList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment