knox-flaneur
knox-flaneur

Reputation: 149

How do I check if an A tag is wrapping around an IMG element?

Given an array of dom elements:

var arr = $("a");

How would you check, within a for loop, whether this A tag is wrapping around an IMG element?

arr[i].has("img")

Doesn't work because it is taking an array element.

Upvotes: 0

Views: 167

Answers (2)

Andre M
Andre M

Reputation: 7546

A jQuery selector returns an array which is overloaded with a number of functions. By taking just one of those indexes you lose those functions. To work around this do:

  $(arr[i]).has("img")

This now results in an array that has jQuery's functions, but only contains the item you passed.

Upvotes: 3

Djaouad
Djaouad

Reputation: 22776

var arr = $('a');
for (var i=0;i<arr.length;i++) {
	if ( $(arr[i]).find('img').length>0 ) {
  	console.log('has img');
  } else {
  	console.log('has no img');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>
  <img/>
</a>

<a></a>

Upvotes: 1

Related Questions