Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrap the text with a div jquery

I have this following text inside a paragraph with a html new line at the end

<p class="pcontainer extend">
    First Text<br />
    Second Text<br />
    Third Text<br />
</p>

Now what I desirely want to do is to wrap those 3 text with a div so the output would be..

<p class="pcontainer extend">
    <div class="wrap">First Text</div><br />
    <div class="wrap">Second Text</div><br />
    <div class="wrap">Third Text</div><br />
</p>

as you can see each text has been wrapped with a div (), is there anyway I could achieve that through jquery or javascript approach?. So far im currently searching around for a solution but so far nothing is match to cater my needs. Any suggestions, recommendation and ideas, would love to hear! Thank you in advance.

like image 474
Juliver Galleto Avatar asked Feb 19 '26 06:02

Juliver Galleto


1 Answers

One possible solution is to filter non-empty text nodes and apply wrap() to them:

$('p').contents().filter(function() {
    return this.nodeType === 3
        && $.trim(this.nodeValue).length;
}).wrap('<div class="wrap" />');

DEMO: http://jsfiddle.net/kEvm4/

like image 164
VisioN Avatar answered Feb 20 '26 20:02

VisioN