Ramya Ramya - 8 months ago 88
jQuery Question

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): ?>
<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
<?php echo $_subcategory->getName() ?>
<?php endforeach; ?>
<?php endforeach; ?>

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

var $j = jQuery.noConflict();
$j(function() {

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



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">

        display : block;

Use jQuery find(),