views:

278

answers:

3

I have multiple div's that look like this:

<div><a href="our_work.html?clientid=39">
<img src="filestore/data_logos/39.gif" alt="client logo"/>
</a></div>

I am trying to get the image src if you click on the div layer:

$('#carousel div').click(function(event) {
  alert($(this).children('img').attr('src'));
});

The alert always comes back as null, any ideas?

+6  A: 

Use this:

$('#carousel div').click(function(event) {
  alert($(this).find('img').attr('src'));
});

The images aren't children of the div...they're children of the <a> which is a child of the div, need to go one more level down.

Nick Craver
+1 - `.children()` will return only **direct descendants** where `.find()` will search through all elements underneath; children, grandchildren, etc.
gnarf
+2  A: 

Try this:

$('#carousel div').click(function(event) {
  alert($('img', this).attr('src'));
});

~Matt

m4olivei
+2  A: 

Straight from the horse's mouth, emphasis mine:

Given a jQuery object that represents a set of DOM elements, the .children() method allows us to search through the immediate children of these elements in the DOM tree...

The IMG is nested like this: DIV > A > IMG; what you need is find() not children().

Piskvor