How to improve this little piece of code

I'm just wondering how to improve this code:

pagination.children('li.active').prev().prev().prev().prev().prevAll('li.pgn').css("display","none"); 

I just don't like the .prev() chain, and I haven't found a way to improve it, but I'm sure you know how .prev()

Edit:

pagination is my ul , which contains a lot of li with someone who has an active class.

I want to highlight all li to li.active , but not the first 5 previous ones.

Example (forget the pgn class):

 <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li class="active"></li> 

This will give the following:

 <li style="displat: none;"></li> <li style="display: none;"></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li class="active"></li> 
+4
source share
4 answers

You can use the selector :gt() .

 pagination.children('li.active').prevAll('li:gt(4)').hide(); 

http://jsfiddle.net/MrvDX/

+3
source

I think the fact that you do it this way indicates that the design of your page / application can be improved.

Why do you need to find an LI with an active class? Why don't you know that? Surely it was your application that generated the markup.

It seems you are trying to determine the state from the markup that I like to avoid. You should have an object that tells you which LI index is selected. Then you can use the much simpler jQ selector to select the indices you are interested in.

+1
source

try it

EDIT

 var pagination = $('ul'); var len = pagination.find('li.active').prevAll('li').length; pagination.find('li.png').slice(0 , len-5).css('display','none')​​​​​​​​​​​​​​​​​; 

WORKING FIDDLE

0
source

You can try something like this ...

 var $prevAll = pagination.children('li.active').prevAll('li.pgn'); var prevCount = $prevAll.length; $prevAll.filter(function(index){ return (prevCount - index < 5) }).hide() //instead of - .css("display", "none"); 

using the filter method and passing it a function.

http://api.jquery.com/filter/

Here is a working example.

http://jsfiddle.net/aTzzK/2/

0
source

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


All Articles