prawwe316 prawwe316 - 2 months ago 8
jQuery Question

Targeting single set of repeating elements using jQuery

I am trying to create individual toggle for elements to show / hide.
All similar elements are responding to the action. How do I make this work for one particular set only? All the similar sections are getting toggled currently

Heres a fiddle of what I have created

https://jsfiddle.net/bqu0hznf/

<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary panel-custom">
<div class="panel-heading">
<div class="img-wrap">
<img src="http://placehold.it/50x50">
</div>
<div class="content-wrap">
<h4 class="panel-title"><a href="javascript:void(0);" class="acc-toggle">Basic panel example</a></h4>
<p>Lorem ipsum dolor blah blah blah....</p>
</div>
</div>
</div>
</div>
</div>

<div class="row">
<div class="col-md-12">
<div class="panel panel-primary panel-custom">
<div class="panel-heading">
<div class="img-wrap">
<img src="http://placehold.it/50x50">
</div>
<div class="content-wrap">
<h4 class="panel-title"><a href="javascript:void(0);" class="acc-toggle">Basic panel example</a></h4>
<p>Lorem ipsum dolor blah blah blah....</p>
</div>
</div>
</div>
</div>
</div>

<div class="row">
<div class="col-md-12">
<div class="panel panel-primary panel-custom">
<div class="panel-heading">
<div class="img-wrap">
<img src="http://placehold.it/50x50">
</div>
<div class="content-wrap">
<h4 class="panel-title"><a href="javascript:void(0);" class="acc-toggle">Basic panel example</a></h4>
<p>Lorem ipsum dolor blah blah blah....</p>
</div>
</div>
</div>
</div>
</div>




<script>
$('.acc-toggle').click(function() {
$( '.panel-custom p , .panel-custom .img-wrap img' ).fadeToggle('fast', 'linear');
});
</script>

Answer

Use $(this).closest('.panel-custom') to find ancestor .panel-custom and then find p, .img-wrap img inside it like following.

$('.acc-toggle').click(function() {
    $(this).closest('.panel-custom').find('p, .img-wrap img').fadeToggle('fast', 'linear');
});

UPDATED FIDDLE