Reputation: 19
function createPicItem(num) {
$("<div></div>")
.addClass("merchPic")
.append($("<img/>")
.attr("src", merch[num].picAdd)
).appendTo("#merchCatalog");
}//End of function CreatePicItem
//--------------------------------------------------
$("#merchCatalog div.merchPic").click(function () {
alert($(this+">img").attr("src"));
});
When the div is clicked I want to alert the src of its inner image.
But when I click it nothing happens... even the alert dialog does not pop up.
What am I doing wrong?
Upvotes: 0
Views: 58
Reputation: 58375
I used find
. The difference between find and children is that find traverses down the DOM. There's not much in it here though so it doesn't matter (but there's an interesting discussion about the speed of the two here)
alert($(this).find("img").attr("src"));
This fiddle shows it in action.
As has been suggested you could equally use children
alert($(this).children("img").attr("src"));
A few things to note though:
It's important that createPicItem()
has run before you set up your click handler ($("#merchCatalog div.merchPic").click
) because otherwise it won't have anything to attach to. A good solution can be seen here.
If you look at the console (developer tools) you will have noticed an error is thrown. The error tells you that your selector $(this+">img")
doesn't work. The moral of the story, check the console!
Upvotes: 0
Reputation: 12025
Try alert($(this).children("img").attr("src"));
This will search for image element in the first level of the div
Upvotes: 1