Flexible plugin for nested table of contents
My partner saw the search results page for this blog and, always on the lookout for a way to improve things, suggested that it would benefit from a table of contents at the top. I could do this with Wordpress, of course, but it sounded like a good idea for a jQuery plugin, too. A little googling showed that there were a couple of existing solutions, but there were two things I wanted that they didn't seem to offer:
- the ability to select via selectors exactly which elements would be included (i.e.,
#content h2instead of justh2) - the ability to nest the lists of sections to reflect the hierarchy of the page
var $toc = $.toc('#content h1, h2, h3.foo');$.toc('h1,h2,h3').prependTo('body').attr('id','toc');Note
$('h1,h2') will return a jQuery object containing all the h1's in a document, followed by all the h2's in a document: h1 h1 h1 h2 h2 h2. I needed all the h1's and h2's in the document in the order they appeared; so, perhaps, h1 h1 h2 h2 h1 h2 h2.
The obvious-in-hindsight answer:
$('h1,h2').addClass('selectedElements');
var selectedElements = $('.selectedElements');