Stefan
Stefan

Reputation: 21

jQuery selector parents and siblings

I have a div structure that I can't change. In an outer-container are two inner-containers. I want to toggle the inner-container2. The button is in the first inner-container.

This structure repeats again and again. So I can't select the classname (inner-container2). This classname appears often.

I must select something like: go one level up from the button and take the next div

<div class="outer-container">
  <div class="inner-container1">
    <div class="button">
    </div>
  </div>
  <div class="inner-container2">
  </div>
</div>

This group comes again and again.

I want to have a script that starts with a click on button and opens only the inner-container2 in the same group.

$(document).on('click', '.button', function(){
  $('?????').toggle('slow');
});

Upvotes: 0

Views: 50

Answers (1)

ankitkanojia
ankitkanojia

Reputation: 3122

$(document).on('click', '.button', function() {
  $(this).parent().next().toggle('slow');
});
.inner-container2{
  background-color:gray;
  height : 50px;
  width : 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="outer-container">
  <div class="inner-container1">
    <div class="button">
      <button>BUTTON1</button>
    </div>
  </div>
  <div class="inner-container2"></div>
</div>

I have made an example using your code just added css to define the functionality.

Upvotes: 2

Related Questions