JQuery detecting a nonexistent element

I have a function that checks if the img tag is inside a picture element with the "colorbox" class, and if so, add some additional styles to some elements. However, the function still works, even if there are no images in the color image, and I don’t know why.

My jQuery looks like

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

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

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

So why will jQuery collect an element that does not exist?

+7
javascript jquery html
source share
3 answers

I would do it like this:

 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 items if any

then you ask if there is a list .has("img") ? this means that if one element in the list contains img inside, then you get true as a result of this if-statement, so your code does not work as expected

+4
source share

I would prefer the find function

 var $img = $(".colorbox").find("img"); if ($img.length) { //exisst } 
+4
source share

Returns a new subset of jquery. You will want if($(".colorbox").has("img").length) to check if there are img tags

+3
source share

All Articles