简体   繁体   中英

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...

DEMO

var span = $('p > span:first')[0];
var target = [];
while(span.nextSibling) {
    target.push(span.nextSibling);
    span = span.nextSibling;
}
$(target).wrapAll('<span />');

This might work

$('<span>').insertAfter('span')
$('</span>').appendTo('p')

You'll want to be more specific with your targetting of course.

Thanks for your help @Sahil Muthoo, @Saul and @puppybeard, unfortunately I had trouble getting your suggested answers working, so at last I came up with this which, allthough looks a bit overdone, works for my case.

See live demo over at jsFiddle.

var p = $('p').clone();
p.children('span').first().replaceWith('[split]');
var aParts = p.html().split('[split]');
var newP = $('<p>').text(aParts[0]).append($('p').children('span').first());
if (aParts.length > 1) {
    newP.append($('<span>').html(aParts[1]));
}       
$('p').replaceWith(newP);

Suggestion for cleaning up the above mess would be appriciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM