MBH
MBH

Reputation: 119

Cannot get src of image using jQuery

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?

Upvotes: 2

Views: 333

Answers (2)

Alsa
Alsa

Reputation: 1

$(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);
});

Upvotes: 0

Linh Hy
Linh Hy

Reputation: 46

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.

Upvotes: 2

Related Questions