如何删除一个 div
中除了具有 class='notsure'
的 div/span
以外的所有内容?我可以使用 empty
删除所有子元素,但不确定如何保留特定的 div
。
<div id="test">
here is a test
<p>a paragraph</p>
<div class="notsure"></div>
</div>
如何删除一个 div
中除了具有 class='notsure'
的 div/span
以外的所有内容?我可以使用 empty
删除所有子元素,但不确定如何保留特定的 div
。
<div id="test">
here is a test
<p>a paragraph</p>
<div class="notsure"></div>
</div>
var save = $('#test .notsure').detach();
$('#test').empty().append(save);
更新:
如果你也想要移除文本 here is a test
:
var notsure = $('.notesure');
$('#test').html('').append(notsure);
$('#test').children().not('.notsure').remove();
试试这个
$("#test").children().filter(":not(.notesure)").remove();
你可以检查下面的工作示例。
$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container');
});
function deleteElementsBelow(parentContainerSelector) {
var save = $('#parent-container #delete-button').detach();
$(parentContainerSelector).empty().append(save);
}
});
你可以筛选它的内容:
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 !!');
}
.notsure
$('.notsure').clone(true).appendTo($('#test').empty());
从clone(true)
中删除true
以摆脱.notsure
的绑定事件,如click等。
如果您对绑定到该元素的事件不感兴趣,可以简单地执行以下操作:
$('.notsure').appendTo($('#test').empty());
这里可以使用一个技巧...
$("#test").html('<div class="notesure">'+$('div.notesure').html()+'</div>')
div.notesure
的任何事件监听器。 - icktoofay