简体   繁体   中英

Get the closest img src inside a div

I need to get the src of an image inside the closest div with the class name "asd" but I keep getting "undefined" returned. Here's my code:

HTML

<div class="asd">
     <img src="https://www.google.com/images/srpr/logo11w.png" alt="test">
</div>
<button type="button" onclick="show()" >test</button>

Javascript

 function show(){
     var url = jQuery(this).closest('.asd').find("img").attr("src");  
     alert(url);
  }

This works: $('.asd').find('img').attr('src'); but it's not what I need. I need it be the closest div. What am I doing wrong?

What about this selector then

$('.asd > img').attr('src');

..?

Document for the jQuery child selector: http://api.jquery.com/child-selector/

prev() will do the trick:

jQuery("#btn").click(function(){
     var url = jQuery(this).prev('.asd').find("img").attr("src");
     alert(url);
});

Fiddle: http://jsfiddle.net/uvxosp7e/

Take a look at jQuery's next and prev selectors. I think that's what you're looking for.

Essentially, they both get the immediately following and preceding sibling of each element in the set of matched elements respectively.

this is referring to the window object, you need to pass a reference:

<button type="button" onclick="show(this)" >test</button>

Then, you can do this: ( closest travels up in the dom tree, not its siblings )

function show(button){
     var url = jQuery(button).prev('.asd').find("img").attr("src");  
     console.log(url);
  }

One solution is to pass this as parameter:

<button type="button" onclick="show(this)" >test</button>

and in js :

window.show = function(obj){
    var url = $(obj).prev().children("img").attr("src");
}

fiddle using prev

Alternative if you want to use closest then you have to change your html structure to following:

<div class="asd">
    <img src="https://www.google.com/images/srpr/logo11w.png" alt="test" />
    <button type="button" onclick="show(this)" >test</button>
</div>

js

window.show = function(obj){
    var url = $(obj).closest(".asd").children("img").attr("src");
}

fiddle using closest

Ref

this refers to the DOM element.

.prev()

.closest()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM