可以使用jQuery 遍历中的 not() 方法来排除某些元素,例如根据元素的id,class等排除,示例代码
$("div.content *").not(".keep"); // 表示content类的div下除keep类以外的所有元素;另外,注意*表示所有元素
下面给出实例演示:删除content类的div下除keep类以外的所有元素
创建Html元素
<div class="box">
<span>点击按钮删除下面绿色框中所有不是keep类的元素,keep类的元素用红色区分。</span><br>
<div class="content">
<input type="checkbox" name="item"><span>萝卜</span>
<input type="checkbox" name="item"><span>青菜</span>
<input type="checkbox" name="item" class="keep"><span class="keep">小葱</span><br>
<input type="checkbox" name="item" class="keep"><span class="keep">豆腐</span>
<input type="checkbox" name="item"><span>土豆</span>
<input type="checkbox" name="item"><span>茄子</span><br>
<input type="text" value="我也不是keep类的">
</div>
<input type="button" value="删除">
</div>设置css样式
div.box{width:300px;height:200px;padding:10px 20px;border:4px dashed #ccc;}
div.box>span{color:#999;font-style:italic;}
.keep{color:red;}
div.content{width:250px;height:100px;margin:10px 0;border:1px solid green;}
input{margin:10px;}
input[type='button']{width:200px;height:35px;margin:10px;border:2px solid #ebbcbe;}编写jquery代码
$(function(){
$("input:button").click(function() {
$("div.content *").not(".keep").each(function() { // "*"表示div.content下的所有元素
$(this).remove();
});
});
})观察显示效果
删除前
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/314e251f95cad1c8b4dc68bf7a3e6709c83d51c6?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
删除后
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/a1ec08fa513d2697d5969cc550fbb2fb4216d8e5?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)