Geek Answers Handbook

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(&quot;http://pinterest.com/pin/create/button/?url=http://mysite.com/some-post&amp;description=Some Description&amp;media=http://mysite.com/path/to/myimage.jpg&quot;,&quot;Pinterest&quot;,&quot;scrollbars=no,menubar=no,width=600,height=380,resizable=yes,toolbar=no,location=no,status=no&quot;);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
javascript jquery html
thindery Dec 03 '12 at 22:29
source share
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
Sushanth - Dec 03 '12 at 10:31
source share

One of the easiest ways is to go to the parent element and search for the image element inside:

 $("div.pinIt").click(function() { var url = $(this).closest("div.showPin").find("img.lazy").attr("src"); alert(url); }); 
+2
VisioN Dec 03 '12 at 22:30
source share

More articles:

  • Python C-Api thread issues - python
  • Problem with added developer portal device - iphone
  • .Net MemoryCache - How to update the expiration time for an existing item? - caching
  • If Powershell is built on top of .NET, what is the reason for writing scripts instead of C # code? - c #
  • Sublime Text open * .handlebars.coffee as HTML file - sublimetext2
  • how to send a request to a torrent tracker server - c
  • Single-line and multi-line loops and vectorization in Python - python
  • Groups of zebra stripe elements li - javascript
  • SQL Server: add row, if it does not exist, increment value of one column, atomic - sql
  • jQuery.load () wait for content to load - jquery

All Articles

Geek Answers | 2019