jquery删除除div之外的所有子节点

cou*_*011 15 jquery

如何删除里面的一切div,除了一个div/span用class='notsure'?我可以删除所有使用empty但不确定如何保存特定的孩子div.

<div id="test">
    here is a test
    <p>a paragraph</p>
    <div class="notsure"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 36

var save = $('#test .notsure').detach();
$('#test').empty().append(save);
Run Code Online (Sandbox Code Playgroud)


Sar*_*raz 13

更新:

如果您还想删除文字here is a test:

var notsure = $('.notesure');
$('#test').html('').append(notsure);
Run Code Online (Sandbox Code Playgroud)

工作实例


$('#test').children().not('.notsure').remove();
Run Code Online (Sandbox Code Playgroud)


Rup*_*war 6

试试这个

$("#test").children().filter(":not(.notesure)").remove();
Run Code Online (Sandbox Code Playgroud)