Choosing <li> in groups of 3

I am trying to select <li> in groups of 3, currently I am using :gt and :lt like this

  $('.events_list li:lt(7):gt(3)').css('display', 'block'); 

This is fine, but it seems like there might be a better way. I just want to press a button and select the next 3 <li> .

+4
source share
4 answers

Try

 var triplet = 0; $('button').click(function(){ $('.events_list li') .hide() // hide the ones that are visible .filter(function(i){ return i >= triplet*3 && i < (triplet+1)*3; // filter the next 3 }) .show(); // and show them triplet++; }); 

demo at http://jsfiddle.net/PyEhU/

+4
source

you can also try nextUntil :

 $('.events_list li:eq(3)').nextUntil('.events_list li:eq(7)').css('display', 'block'); 
0
source
 jQuery("ul li").filter(function(index,el){return index>3 && index<7}).css('display', 'block'); 

Try it.

0
source

Gaby's answer worked well for me (and I would support it if I could), but for my use I needed a loop and one problem with $. the filter is that it iterates over all the elements in each pass of the cycle. So I used slice , which allows you to select elements from a set. It also makes the code a little easier. As an added bonus, I moved the selector from the function, since I assume that the list itself does not change, and therefore there is no need to select it again and again.

This is my version based on Gaby's:

 var triplet = 0; var $elements = $('.events_list li'); $('button').click(function(){ $elements .hide() // hide the ones that are visible .slice( triplet*3, (triplet+1)*3) .show(); // and show them triplet++; }); 

Demo at http://jsfiddle.net/sf3N9/

0
source

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


All Articles