Agyan
adda
Run
Reset
Copy
jQuery Tutorial › jQuery Traversing › Product cards with closest() and find()
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <style> .product{display:inline-block;width:150px;border:1px solid #ddd;padding:10px;margin:5px;border-radius:8px;vertical-align:top} .product.added{border-color:#2b8a3e;background:#ebfbee} </style> <div class="product"><h4 class="name">Pen Drive</h4><p>₹<span class="price">499</span></p><button class="add">Add to cart</button></div> <div class="product"><h4 class="name">Mouse</h4><p>₹<span class="price">349</span></p><button class="add">Add to cart</button></div> <div class="product"><h4 class="name">Keyboard</h4><p>₹<span class="price">899</span></p><button class="add">Add to cart</button></div> <h3>Cart total: ₹<span id="total">0</span></h3> <ul id="cart"></ul> <script> $(function () { let total = 0; $('.add').click(function () { const $card = $(this).closest('.product'); const name = $card.find('.name').text(); const price = Number($card.find('.price').text()); total += price; $card.addClass('added').siblings().removeClass('added'); $('#cart').append($('<li>').text(name + ' – ₹' + price)); $('#total').text(total); $(this).text('Added ✓').prop('disabled', true); }); }); </script>
Result