If you need to do this, why not just use jQuery to replace each of the h2 elements with an anchor a , and then add <br /> after that?
$('h2').after('<br />').replaceWith(function() { return $('<a>', { href: '#', text: $(this).text() }); });
It is much better and cleaner, without the hassle of trying to parse HTML with regular expression. Alternatively, if you need a new ul element with all h2 tags, then use this:
var ul = $('<ul>'); $('h2').each(function(){ $('<a>', { text: $(this).text(), href: '#' }).wrap('<li>').parent().appendTo(ul); });
In addition, anchors and <br> tags in ul lists are not allowed - why not use the elements of the li list?
In fact, the best way to accomplish what you are trying to do here is to use your side code to generate #hash and id for each of the anchor elements and h2 . However, if you want to do this using client-side Javascript, then this would be better:
var ul = $('<ul>'); $('#wrapper h2').each(function(){ var t = $(this); $('<a>', { text: t.text(), href: '#', click: function(e){ $('body').animate({scrollTop: t.offset().top}, 'fast'); e.preventDefault(); } }).wrap('<li>').parent().appendTo(ul); }).prependTo('.left-col');
In addition, you can hide all p elements after each h2 element and show them only when h2 element is pressed
$('.left-col p').hide(); $('.left-col h2').click(function(){ $(this).nextUntil('h2').toggle(); });
The functions fadeToggle() and slideToggle() also available if you want something more unusual.