empty()除特定元素外的所有内容

Fas*_*ack 4 jquery

使用jQuery的empty()方法,我可以阻止从DOM中删除特定元素,同时删除所有其他元素吗?

例如:

<div id="container">
    <div id="noRemove"></div>
    ... more content ...
</div>
Run Code Online (Sandbox Code Playgroud)

当我使用jQuery进行此调用时$("#container").empty(),如何在删除noRemove内部的其余内容时阻止删除container

ban*_*aka 11

您不能empty单独使用该功能.这是你可以做到的一种方式:

var $container = $('#container'),
    $noRemove = $container.find('#noRemove');

$container.html($noRemove);
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴:http://jsfiddle.net/joplomacedo/R4cu5/


Joã*_*lva 7

使用以下内容,它将删除容器中的所有内容,其元素idnoRemove:

$('#container').contents().filter(function () {
    return this.id != "noRemove";
}).remove();
Run Code Online (Sandbox Code Playgroud)

演示.

  • @jnylen:这就是你需要使用`filter()`的原因,**将*处理文本节点. (2认同)