Dr.eel
Dr.eel

Reputation: 1935

jQuery find elements that do not have specified ancestor

I have to find some elements that do not have specified ancestor. Example Code:

<a href="#">
  <img src="pic1.jpg" />
</a>
<p>
  <img src="pic2.jpg" />
</p>

I want to select all img tags not wrapped in a tag.

How can I do it?

Upvotes: 1

Views: 284

Answers (3)

Dr.eel
Dr.eel

Reputation: 1935

I did it with this code:

$("img").filter(function(){
  return $(this).closest('a').length === 0
}).css("border", "3px solid red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">
  <img src="pic1.jpg" />
</a>
<p>
  <img src="pic2.jpg" />
</p>

Upvotes: 4

Mohammad
Mohammad

Reputation: 21499

You can do this work using simpler solution.

Use :not() instead of .filter( function ).

$("img:not(a img)").css("border", "3px solid red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">
  <img src="pic1.jpg" />
</a>
<p>
  <img src="pic2.jpg" />
</p>

Upvotes: 1

kshitij
kshitij

Reputation: 710

Can do using parent also:

var images =  $('img').filter(function(){
  if(!$(this).parent().is('a')) {
    return $(this);  
  }
});

Upvotes: 0

Related Questions