pmn
pmn

Reputation: 2255

Removing all child element except <a> tag

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?

Upvotes: 1

Views: 144

Answers (3)

geekonaut
geekonaut

Reputation: 5954

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)
})

Upvotes: 0

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

Use not to exclude the anchor tags

$("#tagId").children().not('a').remove();

Upvotes: 5

Barmar
Barmar

Reputation: 781974

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>

Upvotes: 2

Related Questions