This is my html code
<div class="w-grid-list">
<article class="w-grid-item">
<div class="w-grid-item-h">
<div class="w-vwrapper">
<div class="w-post-elm">
<img width="350" height="233" src="#" sizes="350px">
</div>
<div class="product_details" style="display: none;">
<div class="w-post-elm post_content usg_post_content_1">
<p class="prod_text desktop_prod_text" style="display: block;">Солодкі млинці з яблучним варенням.<br>
<strong>200 г 714 ккал</strong>
</p>
</div>
</div>
<h2 class="product_title">Млинці з сиром та курагою</h2>
<div class="w-hwrapper">
<div class="w-post-elm">
<span class="w-post-elm-before">Weight: </span>
<span class="woocommerce-product-attributes-item__value">200 g</span>
</div>
</div>
</div>
</div>
</article>
<article class="w-grid-item">
<div class="w-grid-item-h">
<div class="w-vwrapper">
<div class="w-post-elm">
<img width="350" height="233" src="#" sizes="350px">
</div>
<div class="product_details" style="display: none;">
<div class="w-post-elm post_content usg_post_content_1">
<p class="prod_text desktop_prod_text" style="display: block;">Солодкі млинці з яблучним варенням.<br>
<strong>200 г 714 ккал</strong>
</p>
</div>
</div>
<h2 class="product_title">Млинці з сиром та курагою</h2>
<div class="w-hwrapper">
<div class="w-post-elm">
<span class="w-post-elm-before">Weight: </span>
<span class="woocommerce-product-attributes-item__value">200 g</span>
</div>
</div>
</div>
</div>
</article>
</div>
When user clicked on H2 tag (with ‘product_title’ class) , then
hid the DIV element (with class ‘product_details’) of that Article tag
not other Div element outside this Article .tag
This is my jQuery code:
jQuery('.product_details').hide();
jQuery('.product_title').click(function(e){
e.preventDefault();
// hide all span
var $this = jQuery(this).parent().find('div');
jQuery(".product_details").not($this).hide();
// here is what I want to do
$this.toggle();
});
But this code is not working properly
2
Answers
You may use
.prev()
method for this like:Using
$(this)
we are only targetingproduct_details
div before the currently clickedproduct_title
element.The element you want to target is a sibling of the element that triggers the click event, so you can use the .siblings() method to select the previous element, or you can also travel the dom to the parent element (article) then select the element you want to target via .find() method :