Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the "alt" attribute from an image that resides inside an <a> tag

Tags:

jquery

next

this should be fairly simple but for some reason, it doesn't work.

I want to get the "alt" attribute from an image that resides inside an tag

<div id="album-artwork">
<ul>
   <li><a href="link to large image"><img src="thumbnail" alt="description of the image" /></a></li>
   ...
</ul>
</div>



$("#album-artwork a").click(function(e) {
e.preventDefault();

var src = $(this).attr("href");
var alt = $(this).next("img").attr("alt");


alert(src); // ok!
alert(alt); //output: undefined

});

any ideas why next() doesn't work? Is there a better solution out there?

Thanks in advance Marco

like image 621
Marco Avatar asked Oct 07 '10 16:10

Marco


2 Answers

It's because the image tag is inside the ul tag. next only looks for tags at the same level. You'll have to use

var alt = $(this).children("img").attr("alt");

EDIT: included the additional " that was missing

like image 140
Catfish Avatar answered Sep 30 '22 18:09

Catfish


$(this).find('img').attr('alt'); 
like image 44
marko Avatar answered Sep 30 '22 18:09

marko