Skip to content

Instantly share code, notes, and snippets.

@mikofski mikofski/gen_toc.html
Last active Aug 29, 2015

Embed
What would you like to do?
generate table of contents
<html>
<head>
<!-- either head or body -->
<style type="text/css">
.toc_item {
color: green;
}
</style>
<!-- css class -->
</head>
<body>
<div id="toc">
</div>
<!-- TOC -->
<h2 class="toc_item">item #1</h2>
<p>Item 1 is very cool.</p>
<!-- item #1 -->
<h3 class="toc_item">item #2</h3>
<p>Item 2 is super fun.</p>
<!-- item #2 -->
<h2 class="toc_item"><a href="http://www.example.com">item #3</a></h2>
<p>Item 3 is awesome.</p>
<!-- item #3 -->
<!-- content -->
<script>
/* Generate TOC
*
* :param classname: Class to which all TOC items belong.
* :param tocID: ID of the TOC element, should be <div></div>.
*/
function gen_toc(classname, tocID) {
var alltags = document.getElementsByClassName(classname); // all TOC items
var toc_content = "<h2>Table of Contents</h2><ol>"; // inner HTML content of TOC element
var toc_link = ' <a href="#' + tocID + '">(' + tocID + ')</a>'; // link to TOC element for each TOC item
for (var i = 0; i < alltags.length; i++) {
var toc_item = alltags[i].innerText; // just the inner text from the TOC item's element, ie: no links
var toc_item_enc = encodeURIComponent(toc_item).replace(" ", "-").toLowerCase(); // make URL safe ID string
alltags[i].setAttribute("id", toc_item_enc); // set ID of TOC item
alltags[i].innerHTML += toc_link; // add back link to TOC from TOC item
toc_content += '<li><a href="#';
toc_content += toc_item_enc;
toc_content += '">';
toc_content += toc_item;
toc_content += '</a></li>';
};
toc_content += '</ol>';
console.log(toc_content);
var toc = document.getElementById(tocID); // TOC element
toc.innerHTML = toc_content;
};
document.body.onload = gen_toc("toc_item", "toc");
</script>
<!-- toc script -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.