Trying to create a "table of contents" script (see jsbin)

I’m very new to jquery so please bear with me if my code is extremely horrible.

I am trying to create a script that grabs all the h* tags on a page and outputs them into a list.

My current problem is the order in which I’m able to output things in the list, take a look at the list item “h3 again - supposed to go after h4” and you’ll see what I mean.

Appreciate any help on what I can do differently to solve this.


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

Thank you