Reputation: 615
I have a parent container with a lot of elements. I need to toggle some of them by clicking a button located in this container, here's 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 please advice how to toggle elements by class only in the same as button's container with jQuery?
Upvotes: 3
Views: 5377
Reputation: 1650
Try this:
$(".i-am-toggle").
on("click", function () {
$(this).parentsUntil("#myContainer")
.find("div.toggle-me").toggleClass("visible hidden");
});
Upvotes: 1
Reputation: 858
You can use the $.parents() method 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');
});
Upvotes: 1
Reputation: 171689
Something like this should get you started:
$('.i-am-toggle').click(function(){
$(this).closest('.my-container').find('.toggle-me').toggle();
});
Assumes you have multiple "my-container" and want to only toggle instances of visible
and hidden
class within the specific container
Upvotes: 2
Reputation: 4818
Try this code... do you mean like 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>
Upvotes: 2
Reputation: 8386
This is how I did it:
$(".i-am-toggle").click(function(){
$(".toggle-me").toggle();
});
Upvotes: 2