How can I collapse a nested list using jQuery?

Posted by Bradley Herman on Stack Overflow See other posts from Stack Overflow or by Bradley Herman
Published on 2010-04-28T15:30:09Z Indexed on 2010/04/28 15:33 UTC
Read the original article Hit count: 261

Filed under:

I have a nested list:

<ul>
  <li><a href='#'>stuff</a></li>
  <li><a href='#'>stuff2</a></li>
    <ul>
      <li><a href='#'>stuff3</a></li>
    </ul>
  <li><a href='#'>stuff4</a></li>
</ul>

...and want to collapse the nested ul when the li is clicked. Before I was using

$('UL LI').click(function(){
  $(this).next().slideToggle();
});

...but this obviously causes a problem when a li doesn't have a ul nested after it. Is there a better way to do this, or is there a way for me to determine if the object returned by $(this).next() is a UL?

© Stack Overflow or respective owner

Related posts about jQuery