Javascript 如何使用 jquery 从父元素中删除文本(不删除内部元素)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11633610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:36:22  来源:igfitidea点击:

How to remove text (without removing inner elements) from a parent element using jquery

javascriptjquery

提问by user203687

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

想象一下,我有如下内容(修改自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>

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

如何在不影响任何子元素的情况下从 DOM 中删除(仅文本)“第一”、“第二”和“第三”。

回答by James Allardice

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:

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

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

Here's a working example.

这是一个工作示例

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).

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

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

注 2:一些链接问题中的答案显示了与我在此处的答案中的代码类似的代码,但它们使用nodeType常量(例如return this.nodeType === Node.TEXT_NODE)。这是不好的做法,因为版本 9 以下的 IE 没有实现该Node属性。使用整数更安全(可以在DOM level 2 spec 中找到)。

回答by Tim Down

Here's a non-jQuery version which works in all major browsers back to IE 5, just to demonstrate how unscary life without jQuery is.

这是一个非 jQuery 版本,它适用于所有主要浏览器,回到 IE 5,只是为了展示没有 jQuery 的生活是多么可怕。

Demo: http://jsfiddle.net/timdown/aHW9J/

演示:http: //jsfiddle.net/timdown/aHW9J/

Code:

代码:

var el = document.getElementById("foo"), child = el.firstChild, nextChild;

while (child) {
    nextChild = child.nextSibling;
    if (child.nodeType == 3) {
        el.removeChild(child);
    }
    child = nextChild;
}

回答by mgraph

try this :

尝试这个 :

$("#foo").html($("#foo").find("div"));?

demo : http://jsfiddle.net/PXxC4/

演示:http: //jsfiddle.net/PXxC4/

回答by xdazz

You could use this.

你可以用这个。

$("#foo").html($("#foo").children());?