Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve child img src (jQuery)

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?

like image 572
fire Avatar asked Feb 02 '10 17:02

fire


3 Answers

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.

like image 82
Nick Craver Avatar answered Nov 06 '22 12:11

Nick Craver


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().

like image 45
Piskvor left the building Avatar answered Nov 06 '22 13:11

Piskvor left the building


Try this:

$('#carousel div').click(function(event) {
  alert($('img', this).attr('src'));
});
like image 27
m4olivei Avatar answered Nov 06 '22 12:11

m4olivei