Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the first 3 elements in UL only on document load?

I have a List (UL) which has a class of .more_stories the UL contains LI.

I use this code to hide them by default on load:

$('ul.more_stories li').css({'display': 'none'});

Now I want to display the first 3 li items inside the UL after that. How can I do that in jQuery?

-Note: I have several ULs with the same class.

I try that and I get unexpected results..

// more stories
$('ul.more_stories li').css({'display': 'none'});
$('ul.more_stories li:gt(2)').show();

Thanks in advance.

like image 692
Ahmad Fouad Avatar asked Dec 03 '22 10:12

Ahmad Fouad


1 Answers

You want the :lt() selector instead, like this:

$('ul.more_stories li').hide();
$('ul.more_stories li:lt(3)').show();

Or, a bit simpler/faster using .slice():

$('ul.more_stories li').hide().slice(0, 2).show();

This approach hides them all, then using the same set and taking the 0-2 index elements to show.


You can also reverse the approach, never hiding the first 3, like this:

$('ul.more_stories li:gt(2)').hide();

Or, again using .slice():

$('ul.more_stories li').slice(3).hide();

For comments, to make this work across multiple <ul> element, use a .each() loop, like this:

$('ul.more_stories').each(function() {
  $(this).children().slice(3).hide(); 
});
like image 127
Nick Craver Avatar answered May 14 '23 04:05

Nick Craver