Last active
April 21, 2022 17:00
-
-
Save miwebguy/e0e5ac049201c024862dbd971a5dd2ce to your computer and use it in GitHub Desktop.
Simple Table of Contents from Headings
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
//https://stackoverflow.com/questions/187619/is-there-a-javascript-solution-to-generating-a-table-of-contents-for-a-page | |
window.onload = function () { | |
var toc = ""; | |
var level = 0; | |
document.getElementById("VNAArticle").innerHTML = | |
document.getElementById("VNAArticle").innerHTML.replace( | |
/<h([\d])>([^<]+)<\/h([\d])>/gi, | |
function (str, openLevel, titleText, closeLevel) { | |
if (openLevel != closeLevel) { | |
return str; | |
} | |
if (openLevel > level) { | |
toc += (new Array(openLevel - level + 1)).join("<ul>"); | |
} else if (openLevel < level) { | |
toc += (new Array(level - openLevel + 1)).join("</ul>"); | |
} | |
level = parseInt(openLevel); | |
var anchor = titleText.replace(/ /g, "_"); | |
toc += "<li><a href=\"#" + anchor + "\">" + titleText | |
+ "</a></li>"; | |
return "<h" + openLevel + "><a name=\"" + anchor + "\">" | |
+ titleText + "</a></h" + closeLevel + ">"; | |
} | |
); | |
if (level) { | |
toc += (new Array(level + 1)).join("</ul>"); | |
} | |
document.getElementById("toc").innerHTML += toc; | |
} | |
<section class='page'> | |
<details class='fr'> | |
<summary>TOC</summary> | |
<aside id='toc'></aside> | |
</details> | |
<br class='cb'/> | |
</section> | |
<article id='VNAArticle'> | |
<h1></h1> | |
<h2></h2> | |
</article> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment