user4671351
user4671351

Reputation:

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?

Upvotes: 7

Views: 1305

Answers (3)

Rami.Q
Rami.Q

Reputation: 2476

i would do it this way:

jQuery(document).ready(function($){
  $('.colorbox img').each(function(){
      var imageElement = $(this);
      // do whatever you want with this element !
  });
  // OR this way
  $('.colorbox').each(function(){
      var box = $(this);
      if( box.find('img').length ){
          // this means the parent colorBox has at least 1 img-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

Upvotes: 3

Denis Matafonov
Denis Matafonov

Reputation: 2812

I'd prefer find function

var $img = $(".colorbox").find("img");

if ($img.length) { //exisst

}

Upvotes: 4

Requisit
Requisit

Reputation: 64

Has returns a new jquery subset. You'll want if($(".colorbox").has("img").length) to check if there's any img tags in there

Upvotes: 2

Related Questions