tags:

views:

30

answers:

5

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

A: 

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);
Catfish
i've just answered my own question... forgot about siblings and childs... your answer helps confirm my answer. Thanks!
Marco
+1  A: 

Try $(this).find('img') instead to select some element within the link.

Alec
A: 

Won't .next pick up the next element which is the next Li and not the IMG?

Dan
A: 

nevermind... i just got it... i've realized that the img is not a sibling of <a> but a child of <a>

this is the correct syntax

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

or

$('img', this).attr('alt');

Test : http://jsbin.com/amado4

Ninja Dude
jQuery rewrites `$(child, parent)` internally to `$(parent).find(child)`.
Alec