2

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
  • HI, you can use $(this).closest('.col').find('.img-thumbnail').attr('src') Commented Dec 23, 2020 at 5:36
  • @Swati Yes, this one works! Just wondering why mine did not work? shouldn't closest look upward this div? Commented Dec 23, 2020 at 5:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.