Search code examples
jquerytoggleclass

How to toggle nested ul li using jquery/javascript?


I want to keep give toggle function for a nested ul li. In Magento I displayed the categories and its subcategories programatically in phtml like below:

<div class="sidebar-block">
  <ul class="cat-list">
    <?php foreach ($categories as $category): ?>
          <li class="category-li">
             <div class="main-cat" style="font-weight:bold;"> 
                 <?php echo $category->getName()?> </div>
                   <div class="sub-cat" style="display:none;">
                     <ul class="subcat-list">
                       <?php foreach ($_subcategories as $_subcategory): ?>
                        <li>
                            <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
                                 <?php echo $_subcategory->getName() ?>
                            </a>
                        </li>
                       <?php endforeach; ?>
                      </ul>
                </div>
          </li>
<?php endforeach; ?>
  </ul>

I wish to show the inner ul when the outer li is clicked. So I enabled the toggle function using jquery below:

<script>
var $j = jQuery.noConflict();
$j(function() {
    $j('li.category-li').click(function(){
        $j(this).children('ul.subcat-list').toggleClass('active');
    });
});
</script>

But it is not working. Please help me to toggle the inner ul.


Solution

  • children()

    The .children() method differs from .find() in that .children() only travels a single level down the DOM tree, while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

    1. So this won't work as your ul is not a direct a child of li.

    2. Also, your ul is always displayed, but the parent div is hidden. So add .active class to the <div class="sub-cat">

      .active{
          display : block;
      }
      

    Use jQuery find(),

    $j(this).find('div.sub-cat').toggleClass('active');
    

    or

    $j('div.sub-cat',this).toggleClass('active');