Skip to content

Instantly share code, notes, and snippets.

@sbp
Created December 6, 2012 00:26
Show Gist options
  • Save sbp/4220844 to your computer and use it in GitHub Desktop.
Save sbp/4220844 to your computer and use it in GitHub Desktop.
Table of Contents generation in JavaScript using jQuery
function contents() {
var first = $('h2:first');
if (!first) return;
var p = '<p><strong>Contents</strong>';
var ol = '<ol id="contents"></ol>';
first.before('<div class="contents">' + p + ol + '</div>');
var outer = $('#contents');
$('h2, h3, h4').map(function (i) {
var header = $(this);
header.attr('id', 'tmp.' + (i + 1));
var link = '<a href="#tmp.' + (i + 1) + '">' + header.text() + '</a>';
var item = '<li class="' + this.tagName + '">' + link;
if (typeof previous == 'undefined') {
outer.append(item)
} else if (this.tagName > previous) {
$('li:last', outer).append('<ul>' + item + '</ul>')
} else if (this.tagName < previous) {
$('ul:last', outer).parent().after(item)
} else { $('li:last', outer).after(item) }
previous = this.tagName;
});
}
$(document).ready(contents);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment