+2  A: 

You are about to generate invalid HTML. The links must be inside the list elements.

This works:

$('h2').each(function() {
    var text = $(this).text();
    $('<li/>')
        .append($('<a />', {text: text, href:'#'+text.replace(/\s/g, '-')}))
        .appendTo('ul.chapters_list');
});

Live example: http://jsfiddle.net/mL2HV/

Felix Kling
Hey would you know how to also erase all commas with what you did in the .replace() part of the code? so, make all spaces into hyphens, and then ALSO erase all commas. thank you!
android.nick
@android.nick: That would be `replace(/,/g, '')`
Felix Kling
+1  A: 

I think this is what you're after:

$('ul.chapters_list li').each(function() { 
    jLi = $(this); 
    jLi.wrap($("<a>").attr('href','#' + jLi.text().replace(/\s/g,'-') )) 
});
Andrew
+1  A: 

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/

Ender
This will only substitute the first "space". You need to add the *global* modifier to replace all: `/ /g`.
Felix Kling
@Felix Kling - You are correct, thanks for pointing that out. I have modified my answer to fix that error.
Ender