JacobTheDev
JacobTheDev

Reputation: 18510

Reading the IMG within an A on click jQuery

I'm trying to adapt my script to read the alt attribute of an img within an a.

For some reason, this isn't work:

$("#thumbs a").click(function(event) {
    event.preventDefault();
    var title = $(this + " img").attr("alt");
    alert(title);
});

It returns a value of [object Object].

I'd appreciate some help, thanks.

Upvotes: 0

Views: 51

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

$(this + " img") will not select anything so the alert which you are seeing is just an empty jQuery object. You should using $(this).find("img") which will select all the img elements within this i.e the anchor element in this case.

$("#thumbs a").click(function(event) {
    event.preventDefault();
    var title = $(this).find("img").attr("alt");
    alert(title);
});

Upvotes: 1

wsanville
wsanville

Reputation: 37506

You need to change your selector to use the second parameter, which is the context in which to evaluate the selector.

$("#thumbs a").click(function(event) {
    var title = $('img', $(this)).attr("alt");
    alert(title);
});

Working example: http://jsfiddle.net/q4Bsq/2/

Upvotes: 3

Related Questions