jQuery: How to find an image by its src

Jquery

Jquery Problem Overview


I need to find an img by name and src. I have been trying the following to no avail.

var s = $("img[src='/images/greendot.gif'][name='BS']");

The html:

<img alt="This item is active." name="BS" src="/images/greendot.gif"/>

vs

<img alt="This item is not active." name="BS" src="/images/spacer.gif"/>

Jquery Solutions


Solution 1 - Jquery

without seeing the html I would say check your path.

$("img[src$='greendot.gif'][name='BS']")

given the following HTML:

<img src="http://assets0.twitter.com/images/twitter_logo_header.png" name="logo" />

this jquery worked:

var x = $("img[src$='twitter_logo_header.png'][name='logo']");
alert(x.attr("src"));

Solution 2 - Jquery

Try losing the quotes:

var s = $("img[src=../../images/greendot.gif][name=BS]");

Solution 3 - Jquery

Browsers add full path to src, href and similar attributes. So even though element is defined with relative path, in DOM 'src' attribute contains domain name and full path. Using [src$="..."] syntax or specifying full domain name seem to be only options for finding images by src with jQuery.


I might be wrong here. src property of image object reports full path, but the attribute should contain path as specified in the code. [src="relative/path"] works in the latest jQuery version, maybe it was an early version where it didn't work.

Solution 4 - Jquery

Change your img tag like this:

<img src="path/to/imgage/img.jpg" title="img.jpg" />

I mean add to your images title attribute and set them name of file.

When you need to access sertain image you can do it as below:

//Finding image that you need using 'title' attribute; 
var imageTag = $("img[title='imageName']");

//Then if you need to do something with it;
imageTag.attr('src', 'path/to/newImage/newImage.jgp');
imageTag.attr('title', 'newImage.jpg');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkjgillaView Question on Stackoverflow
Solution 1 - JqueryJaredView Answer on Stackoverflow
Solution 2 - Jquerykarim79View Answer on Stackoverflow
Solution 3 - JqueryMikeView Answer on Stackoverflow
Solution 4 - JqueryTurikView Answer on Stackoverflow