Ad

Finding The Amount Of Children In A List

- 1 answer

I am trying to find a way to get the children of a list. I have tried different ways but can never get the correct amount. I get the amount of total children instead of the amount of children for the specific clicked value. Here is an example code:

<li class="category">First
 <ul style="display: none;">
    <li class="category_sub">1</li>
    <li class="category_sub">2</li>
    <li class="category_sub">3</li>
 </ul>
</li>
<li class="category">Second
 <ul style="display: none;">
    <li class="category_sub">1</li>
    <li class="category_sub">2</li>
    <li class="category_sub">3</li>
    <li class="category_sub">4</li>
 </ul>
</li>
<li class="category">Third
 <ul style="display: none;">
    <li class="category_sub">1</li>
    <li class="category_sub">2</li>
    <li class="category_sub">3</li>
    <li class="category_sub">4</li>
    <li class="category_sub">5</li>
 </ul>
</li>

Here is Javascript:

      $('.category').click(function(){
        if($(this).hasClass('active')){
            $('.category').removeClass('hide');
            $(this).removeClass('active');
            $(this).parent().find("ul").hide();
        }else if(!$(this).hasClass('active') && !$(this).hasClass('hide')){
            $('.category').addClass('hide');
            $(this).removeClass('hide');
            $(this).addClass('active');
            $(this).parent().find("ul").toggle();
            $(this).parent().find("ul").css({"padding-top":"15px"});
            alert($(this).parent().find('ul').children().length); 
        }
    });

Here is some CSS:

.category_sub{
  list-style-type: none;
  width: 100%;
  padding-left: 20px;
  height: 40px;
}

.category_sub:hover{
  background-color: #aaa;
  cursor: pointer;
}

.category{
  list-style-type: none;
  width: 100%;
  padding-left: 0px;
  height: 40px;
  color: black;
}

.category.hide{
 display: none;
}

.category.active{
  background-color: #aaa;
}

Here is a Jsfiddle: https://jsfiddle.net/1svvm69r/

Now when I click on first, I expect to see 3 but I get 12. It is counting all the children and not the value clicked. If you look at the JS you will see I am alerting the method to get the value. Any suggestions?

Ad

Answer

This line:

$(this).parent().find('ul')

executes the following actions:

  1. Find the parent of the .category element.
  2. Obtain a collection of all the ul elements that are children of the parent of the .category element.

That is the reason it returns 12 instead of 3. What you want to do is find the ul for the element and not its parent:

$(this).find('ul')

Ad
source: stackoverflow.com
Ad