user3883296
user3883296

Reputation: 3

How to get the attribute of clicked image from a list of images using jquery

I have 5 images in a div

    <div class="myimages">
       <span><a><img src="image1.png" alt="image1"></a></span>
       <span><a><img src="image2.png" alt="image2"></a></span>
       <span><a><img src="image3.png" alt="image3"></a></span>
       <span><a><img src="image4.png" alt="image4"></a></span>
       <span><a><img src="image5.png" alt="image5"></a></span>
    </div>

When I click on the image I want to get the attribute of the image that is clicked. How to get the attribute of the image that has been clicked?

Upvotes: 0

Views: 1437

Answers (3)

CodingIntrigue
CodingIntrigue

Reputation: 78585

Assuming your click is on the <a> tag, use find and prop:

$("a").click(function() {
    console.log($(this).find("img").prop("alt"));
});

Upvotes: 1

Rico
Rico

Reputation: 86

Using .attr() method.

$('.myimages a').click(function(){
   alert($(this).children("img").attr('alt'));
});

http://jsfiddle.net/zsz7p/

Upvotes: 0

Vicky
Vicky

Reputation: 613

Take a look

         $(document).on('click','.myimages a',function(e){

             alert($(this).find('img').prop('src'));

          });

Upvotes: 0

Related Questions