Having anything other than an <li>
as a direct child of a <ul>
is non-compliant HTML. Different browsers may handle that differently, and in my experience, IE in particular will not be happy. you should reverse the order, creating a structure like so:
<ul class="chapters_list">
<li>
<a href="#title-number-one">title number one</a
</li>
<li>
<a href="#and-number-two">and number two</a>
</li>
</ul>
You'll want to do your js like this:
$(function() {
var myUL = $('<ul></ul>');
$('h2').each(function() {
var txt = $(this).text();
var href = txt.replace(/ /g, '-');
myUL.append('<li><a href="#' + href + '">' + txt + '</a></li>');
});
$('body').append(myUL);
});
This will create a ul, the iterate over all you <h2>
's, creating an <li>
for each one. It uses a simple regex / /
to replace the spaces in the text of the <h2>
with hyphens.
Here's a working demo: http://www.jsfiddle.net/n3RMh/1/