Reputation: 2915
How would i grab the text 'Peanut Brownie' when the button is pushed.
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="images/peanutBrownie320x150.jpg" alt="afghan">
<div class="caption">
<h4 class="pull-right">$12.00</h4>
<h4>Peanut Brownie</h4>
<p>One Dozen (12)</p>
<div class="row">
<div class=".col-md-8 addToCart">
<button type="button" class="btn btn-primary">Add to Cart</button>
</div>
</div>
</div>
</div>
</div>
I have tried ...
$( "button" ).on( "click", function()
{
alert( $(this).closest('h4').text() )
});
and a few other tricks but just get an empty alert.
Upvotes: 0
Views: 809
Reputation: 46341
You could get the closest div
that has an h4
, and then the last h4
child of that div
$( "button" ).on( "click", function()
{
alert( $(this).closest('div:has(h4)').children('h4:last-of-type').text() )
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="images/peanutBrownie320x150.jpg" alt="afghan">
<div class="caption">
<h4 class="pull-right">$12.00</h4>
<h4>Peanut Brownie</h4>
<p>One Dozen (12)</p>
<div class="row">
<div class=".col-md-8 addToCart">
<button type="button" class="btn btn-primary">Add to Cart</button>
</div>
</div>
</div>
</div>
</div>
Upvotes: 0
Reputation: 144709
closest
doesn't select the closing matching element, it selects the closest matching parent element. The target element is sibling of the div
parent element. You could code:
$("button").on( "click", function() {
alert( $(this).closest('.row').prevAll('h4').first().text() )
});
Note that I have used .first()
method for selecting the first h4
element as text
method returns textContent of all the selected elements.
Upvotes: 4