You might find a benefit from an existing jQuery plugin that creates a table of contents from the headings, such as http://projects.jga.me/toc/If you don't want to use the plugin directly, you may be able to learn something from the techniques that it uses.