I want to remove all child of an element except <a>
tag, i use
$("#tagId").children().remove();
but it remove all of the children, how can i do it?
答案 0 :(得分:5)
使用not
排除锚标记
$("#tagId").children().not('a').remove();
答案 1 :(得分:2)
使用选择器排除a
:
$("#b").click(function() {
$("#tagID").children(":not(a)").remove();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tagID">
<span>This SPAN should be removed</span><br>
<a href="#">This A should be kept</a><br>
<div>This DIV should be removed</div>
</div>
<button id="b">Click me</button>
&#13;
答案 2 :(得分:0)
有一个不需要jQuery的解决方案:
var container = document.getElementById('container')
Array.from(container.children).filter(function(child) {
return !(child instanceof HTMLAnchorElement)
}).forEach(function(child) {
container.removeChild(child)
})