jQuery 删除除一个 div 外的所有子元素

17

如何删除一个 div 中除了具有 class='notsure'div/span 以外的所有内容?我可以使用 empty 删除所有子元素,但不确定如何保留特定的 div

<div id="test">
    here is a test
    <p>a paragraph</p>
    <div class="notsure"></div>
</div>
7个回答

40
var save = $('#test .notsure').detach();
$('#test').empty().append(save);

13

更新:

如果你也想要移除文本 here is a test

var notsure = $('.notesure');
$('#test').html('').append(notsure);

可运行示例


$('#test').children().not('.notsure').remove();

那不会删除“这里是一个测试”。 - Paolo Bergantino

7

试试这个

$("#test").children().filter(":not(.notesure)").remove();

1

你可以检查下面的工作示例。

$(function () {
$('#delete-button').click(function () {
    deleteElementsBelow('#parent-container');
});

function deleteElementsBelow(parentContainerSelector) {
    var save = $('#parent-container #delete-button').detach();
            $(parentContainerSelector).empty().append(save);
}
});

https://jsfiddle.net/L9vdz7n7/


1

你可以筛选它的内容:

var b = $('#test').contents();

b.filter(function() {  //
    return this.nodeType == 3; //Node.TEXT_NODE
}).remove()
.end().filter(':not(.notesure)').remove(); //Find the elements that don' t have the .notesure class.;


$('.notesure').click(function(){
    $(this).html('clicked !!');
}

示例。http://jsbin.com/urudew/2/edit


1

移除兄弟元素但保留 .notsure

$('.notsure').clone(true).appendTo($('#test').empty());

jsBin演示

clone(true)中删除true以摆脱.notsure的绑定事件,如click等。
如果您对绑定到该元素的事件不感兴趣,可以简单地执行以下操作:

$('.notsure').appendTo($('#test').empty());

-1

这里可以使用一个技巧...

$("#test").html('<div class="notesure">'+$('div.notesure').html()+'</div>')

这将删除附加到 div.notesure 的任何事件监听器。 - icktoofay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接