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{
}

reference attr and trim

Solution 4

JQUERY :

if($('img.optional').attr('src') != "") {
  // Image has src !
} else {
  // Image has not src :'(
}
Share:
24,813
Sam Skirrow
Author by

Sam Skirrow

Musician and Freelance Webdeisgner

Updated on July 18, 2022

Comments

  • Sam Skirrow
    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
    Sam Skirrow over 10 years
    can I do src.length == 0 instead of > 0 so that I have a statement if it has no source?
  • opalenzuela
    opalenzuela over 10 years
    $('img.optional[src=""]') to be more exact
  • Anton
    Anton over 10 years
    @SamSkirrow yes you can