TF120
TF120

Reputation: 317

Each loop to check if image src contains string

I'm trying to create a loop that will check the src of all images and if the src contains "null" it will give that image a placeholder/backup image.

So far I have this code which works, however not all images that contain null have that url, so it's not ideal

    $("img").each(function(){
        if ($(this).attr("src") == "https://image.tmdb.org/t/p/w185null"){
            $(this).attr("src", "/img/imagenotavailable.png");
        }
    });

This is what I've tried using indexOf, however I get "Cannot read property indexOf undefined"

   $("img").each(function(){
        if ($(this).src.indexOf("null")){
            $(this).attr("src", "/img/imagenotavailable.png");
        }
    });

Upvotes: 0

Views: 219

Answers (1)

Deepak
Deepak

Reputation: 1433

Hope this will help you. try this

$('img').each(function(i, elem){

    if(!elem.src || elem.indexOf("null") >= 0) {
         $(element).attr("src", "/img/imagenotavailable.png")
     }
})

Upvotes: 1

Related Questions