JQuery - How to convert html with br's in it to html with p's in it?

Posted by Spines on Stack Overflow See other posts from Stack Overflow or by Spines
Published on 2010-04-22T22:21:23Z Indexed on 2010/04/22 22:23 UTC
Read the original article Hit count: 193

Filed under:

On the my page I have html like this:

hi<br>bye<br>sigh<br>hello <em>tie</em><br>lie 

with jquery, how can I convert it to html like this (basically using p's instead of br's):

<p>hi</p><p>bye</p><p>sigh</p><p>hello <em>tie</em></p><p>lie</p> 

My first attempt at doing this was this code:

$(container).contents().filter(function() {
                var val = this.nodeValue;
                return this.nodeType == TEXT_NODE && $.trim(val).length > 0;
            })
            .wrap('<p></p>')
            .end()
            .filter('br')
            .remove();

This worked for the most part, except that it would put hello and <em>tie</em> in separate p elements.

Does anyone know how I can do this properly?

© Stack Overflow or respective owner

Related posts about jQuery