Search code examples
jqueryslideclosest

jQuery ".closest" doesn't work


I'm recently doing some adjustments to a template. It has this kind of FAQ-section where you click on a question and the answer slides down/shows-

Unfortunately this seems broken. So I thought I could add some jquery to the footer.tpl. This basically works - but it still needs some adjustments.

I thought using .closest() would be the correct choice but...naaa :/ If I leave it out, it runs, but then every li does react. What should I use instead, so only the "closest" li shows/hides?

$(document).ready(function(){
    $(".accordion_current").click(function(){
        $.closest(".accordion_content").slideToggle();
    });
});
<ul class="list-accordion">
	<li>
	    <h3 class="accordion_current">Anfahrt & Messeplan</h3>
	    <ul class="accordion_content">
		<li>
		<p>test</p>
                </li>
            </ul>
	</li>
        <li>
	    <h3 class="accordion_current">Anfahrt & Messeplan</h3>
	    <ul class="accordion_content">
	        <li>
	        <p>test</p>
                </li>
	    </ul>
        </li>
</ul>	


Solution

  • You don't need closest, you need next. With closest you will find parents of the element, but you want to look for a sibling.

    And note that you have to use $(this) and not just $.

    $(function() {
        $(".accordion_current").click(function() {
            $(this).next(".accordion_content").slideToggle();
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <ul class="list-accordion">
      <li>
        <h3 class="accordion_current">Anfahrt & Messeplan</h3>
        <ul class="accordion_content">
          <li>
            <p>test</p>
          </li>
        </ul>
      </li>
      <li>
        <h3 class="accordion_current">Anfahrt & Messeplan</h3>
        <ul class="accordion_content">
          <li>
            <p>test</p>
          </li>
        </ul>
      </li>
    </ul>