Eduard Luca
Eduard Luca

Reputation: 6612

Get img tags which have the same src and rel in jQuery

How can I get all the <img> tags which have the same values in their src and rel attributes?

I've tried something like:

jQuery('img[rel=src]')

But it doesn't appear to be working.

Upvotes: 0

Views: 546

Answers (2)

Krishna sagar
Krishna sagar

Reputation: 170

Here is one way of doing it :

<img src="../images/images/map_ico.png" rel="../images/images/map_ico.png" alt="logo" />   
<img src="../images/images/map_ico.png" alt="logo" />
<img src="../images/images/map_ico.png" rel="../images/images/map_ico.png" alt="logo" />



var imgs=[];
$('img').each(function(){
    if($(this).attr('src')==$(this).attr('rel')){
        imgs.push($(this))
    }
})
//would return 2
alert(imgs.length);

The imgs array will now hold all the image tags that have the same src and alt attributes.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817208

You have to use .filter [docs]:

$('img').filter(function() {
    return this.src === $(this).attr('rel');
});

Note that rel is not a valid attribute for img elements. Therefore you might want to use data-* attributes to store the additional information.

Additional note: this.src will return the absolute URL, even if the src attribute contains a relative URL. If you want to get the actual value of the attribute, you have to use $(this).attr('src').

Upvotes: 3

Related Questions