jquery check if img has src

Sam Skirrow picture Sam Skirrow · Oct 14, 2013 · Viewed 23.3k times · Source

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="" />

Answer

Anton picture Anton · Oct 14, 2013

Try this

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