Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Get image title

Tags:

jquery

attr

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.
    });
});
like image 833
ttmt Avatar asked Nov 27 '12 16:11

ttmt


2 Answers

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

$('img', this).attr('title');
like image 198
Rory McCrossan Avatar answered Nov 12 '22 17:11

Rory McCrossan


You can get img title like this

$(this).find('img').attr('title');
like image 35
arunes Avatar answered Nov 12 '22 18:11

arunes