Marwane
Marwane

Reputation: 189

get img attribute with jquery

I made this code so that if the src of the main img is equal to another img's that img will hide but it hides all of the img

jsfiddle

HTML

<div class="a" >
<img src="a">
</div>

<div class="thumb">
<img src="a">
</div>

<div class="thumb b">
<img src="b">
</div>

CSS

.a{width:400px;height:100px;background-color:black;}
.thumb{width:400px;height:100px;background-color:green;}
.b{background-color:yellow;}

JQUERY

var src = $(".a img").attr('src');

if($(".thumb img").attr('src') == src ) {
$(".thumb").hide();
}

Upvotes: 1

Views: 85

Answers (2)

DaniP
DaniP

Reputation: 38252

The problem here is that you are hiding all the thumb elements with:

$(".thumb").hide();

You need just the ones that match the condition, you can use filter():

$(".thumb").filter(function(){
    return $('img',this).attr('src') == src
}).hide()

Jsfiddle Demo

Upvotes: 1

adeneo
adeneo

Reputation: 318182

You have to iterate and check each image, and only hide the one that matches

var src = $(".a img").attr('src');

$(".thumb").each(function() {
    if ( $('img', this).attr('src') == src ) { 
        $(this).hide();
    }
});

Upvotes: 2

Related Questions