jquery check if img has src
24,813
Solution 1
Try this
$('.optional').each(function () {
if (this.src.length > 0) {
//if it has source
}
});
Solution 2
You can use attribute selector:
$('img.optional[src=""]');
In case that you want select the images that don't have empty src
attributes:
$('img.optional[src!=""]');
Solution 3
if($.trim($(".optional").attr("src")) != "")// check image has src
{
// do your stuff
}
else{
}
Solution 4
JQUERY :
if($('img.optional').attr('src') != "") {
// Image has src !
} else {
// Image has not src :'(
}
Comments
-
Sam Skirrow almost 2 years
I have a carousel of images that are dynamically populated. There is potential for up to 5 images, however, if there is less than 5 images I need to introduce some if statements in my code. Is it possible using jQuery to check if an img src is blank?
For example, if I have an image with class "optional" but it has no url, is there a way to detect this with jQuery?
<img class="optional" src="" />
-
Sam Skirrow over 10 yearscan I do src.length == 0 instead of > 0 so that I have a statement if it has no source?
-
opalenzuela over 10 years
$('img.optional[src=""]')
to be more exact -
Anton over 10 years@SamSkirrow yes you can