title: jQuery Expanding & Collapsing lists
body: <p>The code expands and collapses a list in which list items can have sublists. Any ideas to refactor this code - especially the toggling part. Is it necessary to use closures here ? </p>
  
  <pre><code>$(function()
  {
      $('li:has(ul)')
      .click(function(event){
          if (this == event.target) 
          {
              var that = this;
              $('li:has(ul)').children().filter(':not(:hidden)').parent().each(function(x){
                  if(this != that)
                      toggleList(this);
              });
              toggleList(this);
          }
      })
      .css({cursor:'pointer', 'list-style-image':'url(plus.gif)'})
      .children().hide();
  
      $('li:not(:has(ul))').css({cursor: 'default', 'list-style-image':'none'});
  }); 
  function toggleList(L)
  {
      $(L).css('list-style-image', (!$(L).children().is(':hidden')) ? 'url(plus.gif)' : 'url(minus.gif)');
      $(L).children().toggle('fast');
  }
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>The script works on the following HTML snippet (source: jQuery in Action). Actually I was trying to extend the script given in the book. </p>
  
  <pre><code>      &lt;ul&gt;
          &lt;li&gt;Item 1&lt;/li&gt;
          &lt;li&gt;Item 2&lt;/li&gt;
          &lt;li&gt;
            Item 3
            &lt;ul&gt;
              &lt;li&gt;Item 3.1&lt;/li&gt;
              &lt;li&gt;
                Item 3.2
                &lt;ul&gt;
                  &lt;li&gt;Item 3.2.1&lt;/li&gt;
                  &lt;li&gt;Item 3.2.2&lt;/li&gt;
                  &lt;li&gt;Item 3.2.3&lt;/li&gt;
                &lt;/ul&gt;
              &lt;/li&gt;
              &lt;li&gt;Item 3.3&lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;
            Item 4
            &lt;ul&gt;
              &lt;li&gt;Item 4.1&lt;/li&gt;
              &lt;li&gt;
                Item 4.2
                &lt;ul&gt;
                  &lt;li&gt;Item 4.2.1&lt;/li&gt;
                  &lt;li&gt;Item 4.2.2&lt;/li&gt;
                &lt;/ul&gt;
              &lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;Item 5&lt;/li&gt;
        &lt;/ul&gt;
  </code></pre>