使用jQuery删除元素但保留文本 [英] Remove element with jQuery but leave text

查看:999
本文介绍了使用jQuery删除元素但保留文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的HTML:

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>

我想要做的是使用jQuery删除div中的所有跨度而不管附加的类,但是将文本留在span标签后面。因此,最终结果将是:

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>

我试图使用 unwrap()方法,但它解开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.

推荐答案

jQuery 1.4 +



您不想打开跨度,想要打开其内容:

jQuery 1.4+

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

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

在线演示: http://jsbin.com/iyigi/edit

对于早期版本的jQuery,您可以执行以下操作:

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

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

在线演示: http://jsbin.com/iyigi/40/edit

这篇关于使用jQuery删除元素但保留文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆