Remove element with jQuery but leave text

假如想象 提交于 2019-12-29 03:19:08

问题


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.


回答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




回答2:


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




回答3:


$(mydiv).html($(mydiv).text()) 

should do the trick.



来源:https://stackoverflow.com/questions/2308366/remove-element-with-jquery-but-leave-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!