如何使用jquery从父元素中删除文本(不删除内部元素) [英] How to remove text (without removing inner elements) from a parent element using jquery

查看:115
本文介绍了如何使用jquery从父元素中删除文本(不删除内部元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有以下内容(修改自 http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/

Imagine that I have something like the following (modified from http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/)

<div id="foo">
    first
    <div id="bar1">
        jumps over a lazy dog!
    </div>
    second
    <div id="bar2">
        another jumps over a lazy dog!
    </div>
    third
</div>

如何从中删除(仅限文本)first,second和third DOM不会影响任何子元素。

How can I remove just (only text) "first", "second" and "third" from DOM without affecting any of the child elements.

推荐答案

如果要删除所有子文本节点,可以使用 .contents() 然后 .filter() 将匹配的集合减少到仅文本节点:

If you want to remove all child text nodes you can use .contents() and then .filter() to reduce the matched set to only text nodes:

$("#foo").contents().filter(function () {
     return this.nodeType === 3; 
}).remove();​​​​​​​

这是工作示例

注意:这将保留子元素上的所有现有事件处理程序,使用 .html()不会这样做(因为元素已从DOM中删除并重新添加)。

Note: This will preserve any existing event handlers on the child elements, which answers using .html() will not do (since the elements are removed from the DOM and added back in).

注意2 :一些链接问题的答案显示的代码与我在这里的答案类似,但是他们使用 nodeType 常量(例如返回this.node键入=== Node.TEXT_NODE )。这是不好的做法,因为低于版本9的IE没有实现 Node 属性。使用整数更安全(可以在 DOM级别2中找到)规范)。

Note 2: Answers in some of the linked questions show similar code to that in my answer here, but they use the nodeType constants (e.g. return this.nodeType === Node.TEXT_NODE). This is bad practice since IE below version 9 does not implement the Node property. It's safer to use the integers (which can be found in the DOM level 2 spec).

这篇关于如何使用jquery从父元素中删除文本(不删除内部元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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