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

Marco picture Marco · Oct 7, 2010 · Viewed 67.2k times · Source

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

Answer

Catfish picture Catfish · Oct 7, 2010

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