简体   繁体   English

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

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

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中删除(仅文本)“first”,“second”和“third”而不影响任何子元素。

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 nodeType constants (eg return this.nodeType === Node.TEXT_NODE ). 注2 :一些链接问题中的答案显示的代码与我在这里的答案中的代码相似,但它们使用nodeType常量(例如, return this.nodeType === Node.TEXT_NODE )。 This is bad practice since IE below version 9 does not implement the Node property. 这是不好的做法,因为版本9以下的IE没有实现Node属性。 It's safer to use the integers (which can be found in the DOM level 2 spec ). 使用整数更安全(可以在DOM级别2规范中找到 )。

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;
}

try this : 试试这个 :

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

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

你可以用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM