JQuery finding closest src image to div
if I have the following html:
<div class="showPin"> <div class="pinIt" style="display: none;"> <a href="#" onclick="window.open("http://pinterest.com/pin/create/button/?url=http://mysite.com/some-post&description=Some Description&media=http://mysite.com/path/to/myimage.jpg","Pinterest","scrollbars=no,menubar=no,width=600,height=380,resizable=yes,toolbar=no,location=no,status=no");return false;"><img src="images/pinbutton.jpg" class="pinbuttonImg"></a> </div> <a href="myimage.jpg"> <img class="lazy data-lazy-ready" src="myimage.jpg" data-lazy-type="image" data-lazy-src="http://dev.papermusepress.com/stageblog/wp-content/uploads/2012/11/Fall_baby_shower_mantle2.jpg" alt="Fall Baby Shower Mantle" width="700" height="393" style="display: inline;"> </a> </div> how can I make my alert function work, so it warns img src, which is the actual attachment of the image, which always has class="lazy" .
$('div.pinIt').click(function() { var url = $(this).closest('img.lazy').attr('src'); alert(url); }); everything he alerts me is undefined . what am I doing wrong?
+4
2 answers
$('div.pinIt').click(function() { var url = $(this).next('a').find('img.lazy').attr('src'); alert(url); }); Nearest traverses thru the ancestors . But the image is inside the sibling(anchor tag) div . So try it like this.
If you want to use .closest() then this should work.
$('div.pinIt').click(function() { var url = $(this).closest('.showPin').find('img.lazy').attr('src'); alert(url); }); +7