Created
October 23, 2021 12:34
-
-
Save BiancaNL/dee961b65620a5b37037d4b43f08b48f to your computer and use it in GitHub Desktop.
This file contains 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
<script> | |
// Get ToC div | |
toc = document.getElementById("ToC"); | |
//Add a header | |
tocHeader = document.createElement("h2"); | |
tocHeader.innerText="Table of contents"; | |
toc.appendChild(tocHeader); | |
// Create a list for the ToC entries | |
tocList = document.createElement("ul"); | |
// 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); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: https://projectcodeed.blogspot.com/2020/04/an-automatic-table-of-contents.html