Ayush Baheti Ayush Baheti - 2 months ago 8
CSS Question

select parent element class

My html code is as follows:

<div id="cart-list">
<div class="col-xs-12 product-grid-item">
<span class="product-grid-id" style="display: none;">3</span>
<div class="product-info col-xs-12">
<div class="col-xs-8 product-metadata">
<div class="name">Name</div>
<div class="price">Price</div>
<div class="col-xs-6" id="delete">
<button type="submit" name="delete-btn" id="delete-btn">Delete</button>
</div>

</div>
</div>


</div>
<div class="col-xs-12 product-grid-item">
...
</div>
<div class="col-xs-12 product-grid-item">
...
</div>
<div class="col-xs-12 product-grid-item">
...
</div>
</div>


JQuery is :

$(".product-grid-item").on('click','#delete-btn',function(e) {
e.preventDefault();
var id = $(this).find(".product-grid-id").text();
deleteFromCart(id);
return false;
});


I want on delete button click, it should select the span element with class name product-grid-id and get the text in there, which is 3, in this case and pass it forward..

NOTE : There will be many product-grid-item div's in cart-list div. I need to get the id of the div on which the delete button is clicked. this delete button will be in every product-grid-item

Answer

Your problem is that the span element with the product-grid-id class is not a child of your current button, and also not a direct parent of it, so what you actually need to do is find a relevant parent and then find the span.product-grid-id element inside that parent

To find a parent up the dom-tree you need to use the parents(SELECTOR) function, and there you can use the find(SELECTOR) function to get the element you are looking for.

This is an example: (note that I commented-out the call to deleteFromCart function).

$(".product-grid-item").on('click','#delete-btn',function(e) {
  e.preventDefault();
  var id = $(this).parents('.product-grid-item').find(".product-grid-id").text();
  //deleteFromCart(id);
  console.log(id);
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cart-list">
        <div class="col-xs-12 product-grid-item">
            <span class="product-grid-id"   style="display: none;">3</span>
            <div class="product-info col-xs-12">
                    <div class="col-xs-8 product-metadata">
                        <div class="name">Name</div>
                        <div class="price">Price</div>  
                <div class="col-xs-6" id="delete">
                    <button type="submit" name="delete-btn" id="delete-btn">Delete</button>
                </div>

                    </div>
            </div>


    </div>
<div class="col-xs-12 product-grid-item">
</div>
<div class="col-xs-12 product-grid-item">
</div>
<div class="col-xs-12 product-grid-item">
</div>
    </div>