On Tue, Jan 5, 2010 at 1:01 AM, Tong
<[email protected]> wrote:
> Hi,
>
> I have the following HTML:
>
> <div id="text">
> <strong>Some Text Here</strong>: More Text Here<br />
> <strong>Some Text Here</strong>: More Text Here<br />
> <strong>Some Text Here</strong>: More Text Here<br />
> </div>
>
> How could I use jQuery to wrap each line of text in a <li> and remove
> all the <br /> and finally wrap all the <li> in a <ul>?
>
> Example:
>
> <div id="text">
> <ul>
> <li><strong>Some Text Here</strong>: More Text Here</li>
> <li><strong>Some Text Here</strong>: More Text Here</li>
> <li><strong>Some Text Here</strong>: More Text Here</li>
> </ul>
> </div>
>
This seems to work but I don't know that it's the most efficient method.
$(function()
{
/* grab the text and trim leading & trailing newlines/whitespace
*/
var the_text = $.trim($('#text').html());
/* swap out newlines for closing/opening LI tags
*/
the_text = '<ul><li>' + the_text.replace(/\n/g, '</li><li>') +
'</li></ul>';
/* html() normalises the self-closing '<br />' to '<br>'
*/
$('#text').html(the_text.replace(/<br>/g, ''));
});