Maximilian Both
Maximilian Both

Reputation: 191

jQuery get text value from elements from different divs with same class

<div class="panel">
    <div class="panel-heading item-name">T-shirt1</div>
    <div class="panel-body"><img src="img/shirt1.jpg" class="img-responsive" alt="Image"></div>
    <div class="panel-footer text-center">
        <h5>PRICE: <span class="old-price">$15.32</span></h5>
        <h4>$17.56</h4>
        <button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
    </div>
 </div>
<div class="panel">
    <div class="panel-heading item-name">T-shirt2</div>
    <div class="panel-body"><img src="img/shirt2.jpg" class="img-responsive"  alt="Image"></div>
    <div class="panel-footer text-center">
        <h5>PRICE: <span class="old-price">$21.67</span></h5>
        <h4>$23.15</h4>
        <button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
    </div>
</div>
<div class="panel">
    <div class="panel-heading item-name">T-shirt3</div>
    <div class="panel-body"><img src="img/shirt3.jpg" class="img-responsive" alt="Image"></div>
    <div class="panel-footer text-center">
        <h5>PRICE: <span class="old-price">$16.69</span></h5>
        <h4>$16.80</h4>
        <button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
    </div>
</div>

What I really want is to retrieve the value of each item-name when I click on the Add to cart button. If I click on the first button, I should get T-shirt1, second button should alert T-shirt2, third button => T-shirt3.

Here is my jQuery script.

<script>

$('.add-to-cart').click(function() {
    var itemName = $('.item-name', this).text();
    alert(itemName);
}); 
</script>

Upvotes: 2

Views: 2782

Answers (2)

Justinas Marozas
Justinas Marozas

Reputation: 2654

Go from clicked button up in parents chain until you find .panel and then down in children tree until you find .item.name:

$('.add-to-cart').click(function() {
    var itemName = $(this).parents('.panel').children('.item-name').first().text();
    alert(itemName);
}); 

Upvotes: 1

user7739271
user7739271

Reputation:

You can try this:

$('.add-to-cart').click(function() {
    var itemName = $(this).closest('.panel').find('.item-name').text();
    alert(itemName);
}); 

Usage of the closest method: closest

Upvotes: 3

Related Questions