简体   繁体   中英

how to have a <li> list hidden until the <ul> containing it is clicked

I have subgroups of li rows, contained in some ul lists. When the page opens all of the rows are displayed. I'd like it to have the li's hidden until the ul containing them is clicked.

I know you can use css "display:none" to have them hidden on page open, but being a beginner with javascript I'm not sure how to get the list to expand when its clicked.

Thanks

I'd use toggle along with the gt selector to hide elements beyond a certain number.

 lis = $("li:gt(0)").hide(); $("ul").click(function () { lis.toggle(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Expand</li> <li>A</li> <li>B</li> <li>C</li> <li>D</li> </ul> 

You can try it like,

$('ul.subgroups').on('click',function(){ // will work only if you have at least a single li which is visible
   if ($(this).children('li:hidden').length) {
      $(this).children('li:hidden').show();
   }
});

Snippet,

 $(function() { $('ul.subgroups').on('click', function() { if ($(this).children('li:hidden').length) { $(this).children('li:hidden').show(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Item 1</li> <li>Item 2 <ul class="subgroups"> <li> Sub Item 2-1</li> <li style="display:none"> Sub Item 2-2</li> </ul> </li> <li>Item 3 <ul class="subgroups"> <li> Sub Item 3-1</li> <li style="display:none"> Sub Item 3-2</li> </ul> </li> </ul> 

You can use jQuery toggle for this

 $('li a').click(function(){ $(this).siblings('ul').toggle(); }) 
 ul { padding: 0px; list-style: none; } li { display: block } li ul { display: none; padding-left: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#" title="">first</a> <ul> <li><a href="#" title="">first</a></li> <li><a href="#" title="">second</a></li> <li><a href="#" title="">third</a></li> <li><a href="#" title="">fourth</a></li> <li><a href="#" title="">fifth</a></li> </ul> </li> <li><a href="#" title="">second</a></li> <li><a href="#" title="">third</a> <ul> <li><a href="#" title="">first</a></li> <li><a href="#" title="">second</a></li> <li><a href="#" title="">third</a></li> <li><a href="#" title="">fourth</a></li> <li><a href="#" title="">fifth</a></li> </ul> </li> <li><a href="#" title="">fourth</a></li> <li><a href="#" title="">fifth</a></li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM