Last active
January 6, 2026 15:16
-
-
Save Amitind/010614e9b3da8d486dbd31cfd77d69f0 to your computer and use it in GitHub Desktop.
Table of Content using JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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