test
test

Reputation: 2466

jQuery if img src equals then apply class name each img

Basically my img src looks like this and has class name .pic:

img/folderA/..
img/folderB/..
img/folderC/..
..
img/folderZ/..

and I want add class name each of the img example if imc src equals /folderA/ then add that img class name 'thisisA' etc., i tried something like this but it wont work any help?

    $('.pic').each(function(i){
        var imgSrc = this.src;
        if(imgSrc.indexOf('/folderA/')){
            $(this).addClass('thisisA');
        }
            else if(imgSrc.indexOf('/folderB/')){
            $(this).addClass('thisisB');
        }
});

Upvotes: 3

Views: 2036

Answers (3)

bluetoft
bluetoft

Reputation: 5443

how about this:

http://jsfiddle.net/nZCre/1/

 $('.pic').each(function(i){
        var imgSrc = this.src;
        if(imgSrc.indexOf('/folderA/') > -1){
            $(this).addClass('thisisA');
        }
            else if(imgSrc.indexOf('/folderB/')){
            $(this).addClass('thisisB');
        }
});​

if indexOf returns 0 then it will be false, which is probably what is happening: if(0){dosomething()} will never dosomething();

Upvotes: 0

Aust
Aust

Reputation: 11602

The indexOf method returns the position in the string where what you're looking for is. This can cause some weird issues. For example: 'hello'.indexOf('h'); will return 0 because h is in the first position (index 0) in the string.

That means that if you tested like this:

var str = 'hello';
if(str.indexOf('h')) //indexOf returns 0 which is evaluated as false
  alert('hello');
else
  alert('goodbye');

you would always be alerted goodbye even though you are expecting hello.

In order to help with this, indexOf returns -1 if what you are looking for is not found in the string. So you need to check against that instead. So with your code it would be like:

$('.pic').each(function(i){
    var imgSrc = this.src;
    if(imgSrc.indexOf('/folderA/') != -1){
        $(this).addClass('thisisA');
    }
    else if(imgSrc.indexOf('/folderB/') != -1){
        $(this).addClass('thisisB');
    }
});

Upvotes: 0

Barmar
Barmar

Reputation: 780724

$('.pic').each(function(i){
        var imgSrc = this.src;
        if(imgSrc.indexOf('/folderA/') >= 0){
            $(this).addClass('thisisA');
        }
            else if(imgSrc.indexOf('/folderB/') >= 0){
            $(this).addClass('thisisB');
        }
});

indexOf returns -1 when there's no match, and anything other than 0 is considered "true" by if.

Upvotes: 2

Related Questions