Remove element with jQuery but leave text

17,682

Solution 1

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

Solution 2

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

Share:
17,682
Nathan Kurz
Author by

Nathan Kurz

Co-Founder of KeyPay - Simple, intuitive, cloud-based payroll system for small to medium Australian businesses

Updated on June 23, 2022

Comments

  • Nathan Kurz
    Nathan Kurz almost 2 years

    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.

  • Joel
    Joel about 14 years
    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.
  • Erik
    Erik about 14 years
    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!
  • Sampson
    Sampson about 14 years
    Erik, make sure you're using jQuery 1.4+
  • Harshit Gupta
    Harshit Gupta about 11 years
    it deletes all the span tags :P
  • Sampson
    Sampson about 11 years
    @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?
  • Harshit Gupta
    Harshit Gupta about 11 years
    @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.
  • Uyghur Lives Matter
    Uyghur Lives Matter almost 10 years
    If the text from .text() contains escaped HTML, then using .html(text) will be rendered as actual HTML.
  • Ian Warner
    Ian Warner almost 7 years
    Be careful if the text() in question is just another tag like an <img/> this will remove it