jQuery - Get image title

ttmt picture ttmt · Nov 27, 2012 · Viewed 14k times · Source

Really simple one but I can't work it out.

How do I get the title of the image in the code below from clicking the surrounding <a>

$(this,'img').attr('title');
<ul>
    <li><a href="01.jpg"><img src="01_th.jpg" title="image_1" /></a></li>
    <li><a href="02.jpg"><img src="02_th.jpg" title="image_2" /></a></li>
    <li><a href="03.jpg"><img src="03_th.jpg" title="image_3" /></a></li>
</ul>  
$(function(){
    $('li a').click(function(e) {
        e.preventDefault();
        var img_href = $(this).attr('href');
        var img_title = $(this,'img').attr('title');
        alert(img_title); //undefined.
    });
});

Answer

Rory McCrossan picture Rory McCrossan · Nov 27, 2012

You have to put the context to find within as the second argument:

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