Myles Malloy Myles Malloy - 1 year ago 113
Javascript Question

jQuery detecting non-existent element

I have a function that checks to see if an img tag is inside of a figure element with a class of "colorbox", and if it is, to add some additional styling to some elements. However, the function still runs even if there are no images in the colorbox figure and I don't know why.

My jQuery looks like this

if ($(".colorbox").has("img")) {
~code here~

And here is the colorbox figure, clearly without an img element...

<figure class="colorbox">

So why would jQuery be picking up an element that doesn't exist?

Answer Source

i would do it this way:

  $('.colorbox img').each(function(){
      var imageElement = $(this);
      // do whatever you want with this element !


and now to your problem:


$(".colorbox") returns a list of elements if any

then you ask if the list .has("img") ? this means if one element in the list has an img element inside, then you get a true as a result of that if-statement, this is why your code doesn't work as expected

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download