ttmt
ttmt

Reputation: 4984

jQuery - Get image title

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.
    });
});

Upvotes: 6

Views: 15831

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

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

Upvotes: 10

arunes
arunes

Reputation: 3524

You can get img title like this

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

Upvotes: 3

Related Questions