Reputation: 34158
I have many image elements and want to get a specific image's source where the alternative text is "example".
I tried this:
var src = $('.conversation_img').attr('src');
but I can't get the one I need with that.
How do I select a specific image element based on its alternative text?
Upvotes: 27
Views: 121872
Reputation: 149
If you do not specifically need the alt text of an image, then you can just target the class/id of the image.
$('img.propImg').each(function(){
enter code here
}
I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.
$('img.propImg').each(function(){ //for each loop that gets all the images.
if($(this).attr('src') == "img/{{images}}") { // if the src matches this
$(this).css("display", "none") // hide the image.
}
});
Upvotes: 0
Reputation: 3065
To select and element where you know only the attribute value you can use the below jQuery script
var src = $('.conversation_img[alt="example"]').attr('src');
Please refer the jQuery Documentation for attribute equals selectors
Please also refer to the example in Demo
Following is the code incase you are not able to access the demo..
HTML
<div>
<img alt="example" src="\images\show.jpg" />
<img alt="exampleAll" src="\images\showAll.jpg" />
</div>
SCRIPT JQUERY
var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);
var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );
Output will be
Two Alert messages each having values
Upvotes: 55
Reputation: 6722
$('img.conversation_img[alt="example"]')
.each(function(){
alert($(this).attr('src'))
});
This will display src attributes of all images of class 'conversation_img' with alt='example'
Upvotes: 7
Reputation: 318518
var src = $('img.conversation_img[alt="example"]').attr('src');
If you have multiple matching elements only the src of the first one will be returned.
Upvotes: 2