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?
To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.
Definition and Usage. The required src attribute specifies the URL of the image.
In this article, you will learn how to get and set the image src using jQuery. The attr () method to get and change the image source in jQuery. Use the below script to get image src. Use the below script to set the image src. The following example will change the second image to the first image.
The attr () method to get and change the image source in jQuery. Use the below script to get image src. Use the below script to set the image src. The following example will change the second image to the first image. <title> How to get and set image src attribute example</title>
In jQuery to get images (img) src tags in div element we need to write the code like as shown below. $ ('#divimages').children ('img').map (function () {. return $ (this).attr ('src') }).get () If you want complete example to get image tags in particular div we need to write the code like as shown below. <html>.
The :image selector selects input elements with type=image. Syntax $(":image") ❮ jQuery Selectors NEW We just launched W3Schools videos Explore now
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
$('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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With