Better readability for multiple .add with .eq in it

I’m collecting multiple li into one object for a pagination.

var li = $(this).find('li');
if(li.length > 15) {
    var activeId = li.filter('.active').index();
    li.each(function() {
        // do something...

HTML example:

    <li><a href="#…">1</a></li>
    <li class="active"><a href="#…">2</a></li>
    <li><a href="#…">3</a></li>
    <li><a href="#…">4</a></li>
    <li><a href="#…">5</a></li>
    <li><a href="#…">16</a></li>

But this looks quite straight forward and not very performant and readable. So i’m searching for a method to write this code more readable.


To reduce your jQuery Array collection to a specific start-end index set of Elements – you can use Array.prototype.slice(beginIndex, endIndex(not inclusive))

$("ul").each(function() {

  var $li = $(this).find('li'),
      tot = $li.length;

  if (tot > 15) {

    var idx  = $li.filter('.active').index(),
        first3   = $li.slice(0, 3),                                         // Slice
        middle7  = $li.slice(Math.max(0, idx - 3), Math.min(tot, idx + 4)), // Slice
        last3    = $li.slice(tot - 3, tot),                                 // Slice
        $group   = first3.add( middle7 ).add( last3 );                 // Group them

    $group.addClass("dosomething").each(function() {
       // do something on that group of LI elements


}); {
  color: red;

.dosomething {
  color: blue;
<script src=""></script>

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

P.S: if at any time you need to target the LI that are not in our $group you can simply do:

var $allOther = $li.not( $group );