使用 jQuery 删除元素但保留文本

发布于 2024-08-22 19:41:40 字数 430 浏览 3 评论 0原文

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

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

我想要做的是使用 jQuery 删除 div 中的所有 span,无论附加的类如何,但将 span 标记中的文本留在后面。所以最终的结果将是:

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

我尝试使用 unwrap() 方法,但它解开了 div。我还尝试删除这些元素,但这会删除元素及其文本。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

飘过的浮云 2024-08-29 19:41:40

jQuery 1.4+

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

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

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

jQuery 1.2+

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

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

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

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

子栖 2024-08-29 19:41:40

难道一个简单的 $('#my-div').text ($('#my-div').text ()) 就足够了,而不需要解包吗?

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

百善笑为先 2024-08-29 19:41:40
$(mydiv).html($(mydiv).text()) 

应该可以解决问题。

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

should do the trick.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文