jQuery Toggle Help

I have the following code:

$(document).ready(function() {


  // Manage sidebar category display
  jQuery("#categories > ul > li.cat-item").each(function(){
    var item;
    if ( jQuery(this).has("ul").length ) {   
      item = jQuery("<span class='plus'>+</span>").click(function(e){
        jQuery(this)
          .text( jQuery(this).text() === "+" ? "-" : "+" )
          .parent().next().toggle();
        return false;
      });

      jQuery(this).find(".children").hide();
    } else {
      item = jQuery("<span class='plus'>&nbsp;</span>");
    }

    jQuery(this).children("a").prepend( item );
  });

});

This creates a sort of toggle system for my categories. But it will only work with 2 levels deep, what I need it to do is work with unlimited levels.

The HTML:

<li id="categories">
    <ul>
        <li class="cat-item"><a href="#">Link</a>
            <ul>
                <li class="cat-item"><a href="#">Link</a></li>
                <li class="cat-item"><a href="#">Link</a></li>
                <li class="cat-item"><a href="#">Link</a></li>
                <li class="cat-item"><a href="#">Link</a></li>
            </ul>
        </li>
        <li class="cat-item"><a href="#">Link</a>
            <ul>
                <li class="cat-item"><a href="#">Link</a></li>
                <li class="cat-item"><a href="#">Link</a></li>
                <li class="cat-item"><a href="#">Link</a></li>
                <li class="cat-item"><a href="#">Link</a>
                    <ul>
                        <li class="cat-item"><a href="#">Link</a></li>
                        <li class="cat-item"><a href="#">Link</a></li>
                        <li class="cat-item"><a href="#">Link</a></li>
                        <li class="cat-item"><a href="#">Link</a></li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
</li>

Answers


Your top selector is to specific:

jQuery("#categories li.cat-item").each(function(){
    var item = jQuery("<span>").addClass('plus'),
        that = jQuery(this);

    if ( that.has("ul").length ) {   
        item.click(function(e){
            var self = jQuery(this);
            self.text( self.text() === "+" ? "-" : "+" )
                .parent().next().toggle();
            e.preventDefault();
        }).text('+');

        that.find(".children").hide();
    }

    that.children("a").prepend( item );
});

I also change it to cache $(this)


Need Your Help

How to execute JUnit and TestNG tests in same project using maven-surefire-plugin?

unit-testing maven-2 testng junit4 maven-surefire-plugin

Right now I have both type of tests but when I say "mvn test" it only executes TestNG tests and not Junit. I want to execute both one after another. Any Idea ?