Jquery check if img src has

I have a carousel of images that are dynamically populated. There is potential for up to 5 images, however, if there are less than 5 images, I need to enter some if statements in my code. Is it possible to use jQuery to check if img src is there?

For example, if I have an image with the "optional" class, but it does not have a url, is there a way to detect this with jQuery?

<img class="optional" src="" /> 
+7
jquery image src
source share
5 answers

try it

 $('.optional').each(function () { if (this.src.length > 0) { //if it has source } }); 
+12
source share

You can use attribute selector:

 $('img.optional[src=""]'); 

If you want to select images that do not have empty src attributes:

 $('img.optional[src!=""]'); 
+6
source share
 if($.trim($(".optional").attr("src")) != "")// check image has src { // do your stuff } else{ } 

link attr and trim

+2
source share

JQUERY:

 if($('img.optional').attr('src') != "") { // Image has src ! } else { // Image has not src :'( } 
0
source share

you can use

 img[src=""] { display: none; } 

The above selector will just match if the src attribute doesn't matter.

0
source share

All Articles