Shahrzad Parvizi
Shahrzad Parvizi

Reputation: 19

Get access to the child of a div in jquery

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

Answers (2)

jcuenod
jcuenod

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:

  1. 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.

  2. 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

Alon Eitan
Alon Eitan

Reputation: 12025

Try alert($(this).children("img").attr("src")); This will search for image element in the first level of the div

Upvotes: 1

Related Questions