$('h2').each(function() {
$('UL.chapters_list').append($('<li/>', {text: $(this).text()}))
});
This code grabs all of the <H2> tags on the page, then copies each of them to their own <LI> inside of <UL class="chapters_list">, so essentially it creates a list of all the <H2> tags.
I need to wrap each <LI> tag that it creates, with an anchor link, this link should have the text of the <h2> that it grabbed, but replacing the spaces in the <h2> with hyphens '-'
So let’s say my script sees 2 <H2> tags on the page, so it grabs the texts of those <H2> tags and copies them to:
<UL class="chapters_list">
<LI>title number one</LI>
<LI>and number two</LI>
</UL>
I need it to now wrap each of those
so the above will turn into:
<UL class="chapters_list">
<a href="#title-number-one">
<LI>title number one</LI>
</a>
<a href="#and-number-two">
<LI>and number two</LI>
</a>
</UL>
Can anyone help? it shouldn’t be too hard, with the code i’ve provided, thank-YOU.
You are about to generate invalid HTML. The links must be inside the list elements.
This works:
Live example: http://jsfiddle.net/mL2HV/