I have headers in through
tags. Is there a way that I can use JavaScript to generate a table of contents for the contents tha
I've modified the function in AtesGoral's accepted answer to output correctly nested lists and valid HTML5.
Just add the code below to your scripts and call TableOfContents(container, output);
on load, where container is the class or id of your content element and output is the class or id of the TOC element. Default values are '#contents' and '#toc', respectively.
See http://codepen.io/aufmkolk/pen/RWKLzr for a working demo.
function TableOfContents(container, output) {
var toc = "";
var level = 0;
var container = document.querySelector(container) || document.querySelector('#contents');
var output = output || '#toc';
container.innerHTML =
container.innerHTML.replace(
/([^<]+)<\/h([\d])>/gi,
function (str, openLevel, titleText, closeLevel) {
if (openLevel != closeLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(openLevel - level + 1)).join('');
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join('
');
} else {
toc += (new Array(level+ 1)).join('');
}
level = parseInt(openLevel);
var anchor = titleText.replace(/ /g, "_");
toc += '- ' + titleText
+ '';
return '
'
+ titleText + ' ';
}
);
if (level) {
toc += (new Array(level + 1)).join('');
}
document.querySelector(output).innerHTML += toc;
};