Demuri Celidze
Demuri Celidze

Reputation: 615

How to toggle all .class elements in the parent container

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

Answers (5)

brroshan
brroshan

Reputation: 1650

Try this:

$(".i-am-toggle").
   on("click", function () {
      $(this).parentsUntil("#myContainer")
       .find("div.toggle-me").toggleClass("visible hidden");
});

Fiddle

Upvotes: 1

mac
mac

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

charlietfl
charlietfl

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

Bhavin Solanki
Bhavin Solanki

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

Ahs N
Ahs N

Reputation: 8386

This is how I did it:

$(".i-am-toggle").click(function(){
    $(".toggle-me").toggle();
});

Here is the JSFiddle demo

Upvotes: 2

Related Questions