Muleskinner
Muleskinner

Reputation: 14468

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

Upvotes: 4

Views: 763

Answers (3)

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

DEMO

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

Upvotes: 7

Muleskinner
Muleskinner

Reputation: 14468

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.

Upvotes: 0

daveyfaherty
daveyfaherty

Reputation: 4613

This might work

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

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

Upvotes: 2

Related Questions