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?
使用not
排除锚标签
$("#tagId").children().not('a').remove();
Use a selector to exclude a
:
$("#b").click(function() { $("#tagID").children(":not(a)").remove(); });
<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>
There's a solution that does not require jQuery:
var container = document.getElementById('container')
Array.from(container.children).filter(function(child) {
return !(child instanceof HTMLAnchorElement)
}).forEach(function(child) {
container.removeChild(child)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.