Jakub Wilk Jakub Wilk - 5 months ago 13
Javascript Question

Single slideToggle() for the same elements

I have this code HTML:

<div>
<div>
<button class="btn-slide"><span class="fa fa-caret-down" aria-hidden="true"></span></button>
</div>
<div class="block">
...
</div>
</div>


And I have several such elements in my forum template. I use standard js toggle() script:

$(document).ready(function() {
$('btn-slide').click(function() {
$('.block').slideToggle(50);
});
});


And when I click on button all components show or hide but I want to hide/show only this element which I choose. I thought that I can use $(this).childern in 3rd line but if you see .block isn't a btn-slide childern. So how can I achieve what I want?

Answer

You can use parents() next()

$(document).ready(function() {
  $('.btn-slide').click(function() {
    $(this)
      // get all div in parent level
      .parents('div')
      // get immediate sibling after the element with class block
      .next('.block')
      .slideToggle(50);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div>
    <button class="btn-slide"><span class="fa fa-caret-down" aria-hidden="true"></span>
    </button>
  </div>
  <div class="block">
    ...
  </div>
</div>

<div>
  <div>
    <div>
      <div>
        <button class="btn-slide">
          <span class="fa fa-caret-down" aria-hidden="true"></span>
        </button>
      </div>
    </div>
  </div>
  <div class="block">
    ...
  </div>
</div>