Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I collapse a nested list using jQuery?

Tags:

jquery

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?

like image 211
Brad Herman Avatar asked Apr 28 '10 15:04

Brad Herman


3 Answers

if($(this).next().is("ul")) {

}

Should do the trick. See: http://api.jquery.com/is/

like image 94
Jan Jongboom Avatar answered Nov 03 '22 01:11

Jan Jongboom


$('LI').toggle(function() {
    $(this).children('ul').slideUp();
},
function() {
    $(this).children('ul').slideDown();
});

This is assuming that you mean the UL listed under the LI that is clicked. If you want a particular UL to collapse whenever any LI is clicked, you might have to write something with a few more checks.

like image 38
dclowd9901 Avatar answered Nov 03 '22 00:11

dclowd9901


can it be just $(this).next("ul").slideUp()

like image 38
JiJ Avatar answered Nov 03 '22 01:11

JiJ