How to display the first 3 elements in UL only when loading a document?

I have a List (UL) that has a .more_stories class, UL contains LI.

I use this code to hide them by default at boot time:

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

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

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

I try to do this and get unexpected results.

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

Thanks in advance.

+3
source share
1 answer

Instead, you want to select :lt(), for example:

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

Or, a little easier / faster using .slice():

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

This approach hides them all and then uses the same set and displays index elements 0-2.


, 3, :

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

, .slice():

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

, <ul>, .each(), :

$('ul.more_stories').each(function() {
  $(this).children().slice(3).hide(); 
});
+15

Source: https://habr.com/ru/post/1778083/


All Articles