Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Remove element with jQuery but leave text

I've got some html that looks like this:

<div>
    <span class="red">red text</span> some more text <span class="blue">blue text</span>
</div>

What I want to do is use jQuery to remove all the spans within the div regardless of attached class, but leave the text within the span tags behind. So the final result will be:

<div>
    red text some more text blue text
</div>

I've tried to use the unwrap() method but it unwraps the div. I've also tried to remove the elements but that removes the elements and their text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

jQuery 1.4+

You don't want to unwrap the span, you want to unwrap its contents:

$("span").contents().unwrap();

Online Demo: http://jsbin.com/iyigi/edit

jQuery 1.2+

For earlier versions of jQuery, you could do the following:

$("span").replaceWith(function () {
    return $(this).text();
});

Online Demo: http://jsbin.com/iyigi/40/edit


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...