简体   繁体   中英

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?

I'd prefer find function

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

if ($img.length) { //exisst

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM