Switching the list, clicking on an element shows all subelements, and not just subelements from an element

Sorry for the vague title, but I could not find a suitable name, explaining the problem well.

Problem: I wrote code that switches lists. It works the way I want it. When I click on "headcategory", it opens subcategories, etc. The problem occurs when I first click on the headcategory, it opens every list that I don’t want. When I close and open it again, it works as it should. I am trying to understand why this is so, but I have no idea. Therefore, if someone can help me, he / she will be very grateful.

JQuery code

$(document).ready(function()
{
$('ul.subcat').hide();

$('li').click(function(event)
{ 
    event.stopPropagation();
    $('ul', this).toggle(); 

});
});

HTML code

<ul class="headcat">
  <li>item 1
  <ul class="subcat">
    <li>subitem 1
    <ul class="subcat">
      <li>subsubitem 1
      <ul class="subcat">
        <li><p>text</p></li>
      </ul>
      </li>
      <li>subsubitem 2
      <ul class="subcat">
        <li><p>text</p></li>
        <li>subsubsubitem 1
        <ul class="subcat">
          <li><p>text</p></li>
        </ul>
        </li>
        <li>subsubsubitem 2</li>
      </ul>
      </li>
    </ul>
    </li>
    <li>item 2</li>
  </ul>
  </li>
</ul>  
+3
source share
2 answers

li, :

$(this).children("ul").toggle();

: > .

$('> ul', this).toggle(); 

+4

subcat init:

$('ul.subcat:first').hide();

DEMO : http://jsfiddle.net/kv4dT/

0

All Articles