Myles Malloy Myles Malloy - 3 months ago 29
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

jQuery(document).ready(function($){
if ($(".colorbox").has("img")) {
~code here~
}
}


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

<figure class="colorbox">
<ficaption>
<h2></h2>
<p></p>
<p></p>
</figcaption>
</figure>


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

Answer

i would do it this way:

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

}

and now to your problem:

$(".colorbox").has("images");

$(".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