How to switch all .class elements in parent container
I have a parent container with a lot of items. I need to toggle some of them by clicking a button located in this container, here is an example
<div class="my-container">
<a href="/">Home</a>
<div class="toggle-me visible">1</div>
<div class="toggle-me hidden">2</div>
<div>
<strong>Press me</strong>
<button class="i-am-toggle">Toggle</button>
</div>
</div>
Can you provide any advice on how to switch elements by class only in the same container with jQuery?
+3
Demuri celidze
source
to share
5 answers
Something like this should start:
$('.i-am-toggle').click(function(){
$(this).closest('.my-container').find('.toggle-me').toggle();
});
This assumes you have multiple "my-containers" and only want to switch instances of classes visible
and hidden
in a specific container
+2
charlietfl
source
to share
This is how I did it:
$(".i-am-toggle").click(function(){
$(".toggle-me").toggle();
});
Here is a JSFiddle demo
+2
Ahs N
source
to share
Try this code ... you mean this
$('.i-am-toggle').on('click', function(){
$('.my-container div.toggle-me').toggle();
})
.visible{
display:block;
}
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-container">
<a href="/">Home</a>
<div class="toggle-me visible" >1</div>
<div class="toggle-me hidden">2</div>
<div>
<strong>Press me</strong>
<button class="i-am-toggle">Toggle</button>
</div>
</div>
+2
Bhavin solanki
source
to share
You can use the $ method . parents () to find parents relative to your button element. Try something like this:
$('.i-am-toggle').click(function(e){
$(this).parents('.my-container').find('.toggle-me').toggleClass('visible').toggleClass('hidden');
});
+1
mac
source
to share
Try the following:
$(".i-am-toggle").
on("click", function () {
$(this).parentsUntil("#myContainer")
.find("div.toggle-me").toggleClass("visible hidden");
});
Fiddle
+1
brroshan
source
to share