Cannot get src of image using jQuery

Viewed 138

I have a close button which is used to get an image src positioned just above it:

<div class="col">
    <img class="img-thumbnail" src="/path/to/image2.gif">
    <br>
    <span class="img-remove">x</span>
</div>

jQuery:

$(document).on('click', '.img-remove', function () {
    let _self = this;
    let img_src = $(this).closest('.img-thumbnail').attr("src");
    console.log('img_src', img_src);
});

However instead of src value I get this in console:

img_src undefined

What is wrong here and how can I fix it?

2 Answers

Change $(this).closest('.img-thumbnail') to $(this).siblings('.img-thumbnail') will solve your issue

Example code:

$(document).on('click', '.img-remove', function () {
    let _self = this;
    let img_src = $(this).siblings('.img-thumbnail').attr("src");
    console.log('img_src', img_src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
    <img class="img-thumbnail" src="/path/to/image2.gif">
    <br>
    <span class="img-remove">x</span>
</div>


Explain:

$(this) is span.img-remove, .closet() will traversing up through its ancestors. But you need to find img.img-thumbnail, it's sibling of $(this) not ancestors. So you need to use .siblings() to find the sibling.

$(document).on('click', '.img-remove', function() {
  let _self = this;
  let img_src = $(this).closest('.col').find('.img-thumbnail').attr("src");
  console.log('img_src', img_src);
});
Related