Generate Table of Contents from Heading Tags in JavaScript

I recently needed a way to generate a Table of Contents in some documentation. I wanted it to be automatic so I could freely write without having to worry about updating the table of contents. This turned out to be more difficult than I intended with very little available through Google. So I wrote my own function and making it available here for free!


Set the innerHTML of a DOM node to the string returned from generateTOC where you want the Table of Contents to appear. Pass the parent DOM node into the function and optionally a start tag number if you want to start the table of contents at <h2> instead of “

//save references to our DOM nodes
var navNode = document.getElementById("nav");
var parentNode = document.getElementById("content");

//generate the TOC and set the nav innerHTML to it
var generatedHTML = generateTOC(parentNode);
navNode.innerHTML = generatedHTML;

Feel free to direct all questions to the gist.