Behseini Behseini - 7 months ago 10
Javascript Question

Having Issue On Getting alt of Closest Image to buttons

I have a set of panels includinf buttons and images , now I need to get the

alt
attribute of each image close to the clicked button

<div class="panel panel-default">
<div class="panel-heading clearfix">
<button type="button" class="btn btn-danger btn-xs pull-right btn-delete-img" data-id="pmkLips">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
<div class="panel-body">
<img src="../img/pmkLips/img.png" class="img-responsive" alt="sample Data">
</div>
</div>


I tried this

$(function() {
$(".btn-delete-img").on("click", function(){
var imgName = $(this).next('img').attr('alt');
});


and

$(function() {
$(".btn-delete-img").on("click", function(){
var imgName = $(this).find('img').attr('alt');
});


but I am getting


img: undefined


in the console. Can you please let me know what I am doing wrong here?

Answer

Use closest('.panel') to find ancestor .panel and then find img in it like following.

$(".btn-delete-img").on("click", function () {
    var imgName = $(this).closest('.panel').find('img').attr('alt');
    alert(imgName);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="panel panel-default">
    <div class="panel-heading clearfix">
        <button type="button" class="btn btn-danger btn-xs pull-right btn-delete-img" data-id="pmkLips">
            <span class="glyphicon glyphicon-trash" aria-hidden="true">Click</span>
        </button>
    </div>
    <div class="panel-body">
        <img src="../img/pmkLips/img.png" class="img-responsive" alt="sample Data">
    </div>
</div>