30

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.

lomaxx
  • 113,627
  • 57
  • 144
  • 179

3 Answers3

87

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

Community
  • 1
  • 1
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • From the documentation: *Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.* So I guess that's how it's supposed to work. If there was a way to select the text node then you could use unwrap. – Joel Feb 22 '10 at 02:01
  • 1
    Doesn't actually seem to work, just gave it a try on the example HTML from above. EDIT: I was using 1.3.2, guess time to upgrade! – Erik Feb 22 '10 at 02:07
  • Erik, make sure you're using jQuery 1.4+ – Sampson Feb 22 '10 at 02:08
  • it deletes all the span tags :P – Harshit Gupta Mar 29 '13 at 16:22
  • @harshitgupta It should just replace the tags with their contents. I just checked the demo again and it seems to work as advertised. Are you experiencing a total loss of content? – Sampson Mar 29 '13 at 21:21
  • @JonathanSampson no no dont get me wrong....actually your code delete all the span tags existing in the file, without loosing their data which is as expected from the code. My requirement was to delete span tag related to a particular class. And i was able to do that with help. thanks a lot. – Harshit Gupta Apr 02 '13 at 09:28
  • Be careful if the text() in question is just another tag like an this will remove it – Ian Warner May 31 '17 at 21:24
1

Wouldn't a simple $('#my-div').text ($('#my-div').text ()) suffice, without resorting to unwrapping?

K Prime
  • 5,809
  • 1
  • 25
  • 19
-1
$(mydiv).html($(mydiv).text()) 

should do the trick.

Undo
  • 25,519
  • 37
  • 106
  • 129
Tigertron
  • 628
  • 6
  • 6