Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Jquery, how do I wrap part of paragraph text inside span

How do I wrap the innerhtml found after a span in a paragraph inside a span. Better explained by example:

<p>foo <span>bar</span> baz</p>

I want to get:

<p>foo <span>bar</span><span> baz</span></p>

baz is possible marked up as well (ie can contain links etc).

Ive tried

$(p span).first().contents().filter(function() {
    return this.nodeType == 3;
}).text();

But only gives me the inner span text of first span...

like image 978
Muleskinner Avatar asked Jan 19 '23 17:01

Muleskinner


1 Answers

DEMO

var span = $('p > span:first')[0];
var target = [];
while(span.nextSibling) {
    target.push(span.nextSibling);
    span = span.nextSibling;
}
$(target).wrapAll('<span />');
like image 178
Sahil Muthoo Avatar answered Jan 21 '23 07:01

Sahil Muthoo