简体   繁体   中英

Add Class to the first 5 elements within a div with jQuery

I swear I've done this before, but I'm trying to count the first 5 items within a div and then add a class to them and then add a class to the rest.

I have this:

var counter = 0;
$('.images img').each(function(i) {
   if (i == 0) {
       counter = 0;
   } else {
       counter++;
   }
   if (counter < 5) {
       $(this).addClass('this');
   } else {
     $(this).addClass('other');
   }
});

which works, but I feel that it could be cleaned up a bit. Any suggestions to make this a bit leaner?

使用jQuery时,您可以使用:lt() (索引从零开始)

$('.images img:lt(5)').addClass('this')

Easiest solution is to not use JavaScript, but just use a CSS Selector. nth child will let you target a range of items.

 li { background-color: yellow; } li:nth-child(-n+5) { background-color: green; } 
 <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul> 


If you want to use jQuery, you can simplify it with .slice(start, end)

 var lis = $('li'); lis.slice(0,5).addClass('on'); lis.slice(5).addClass('off'); 
 .off { background-color: yellow; } .on { background-color: green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul> 


or you can use the function option in .addClass(function)

 $('li').addClass( function (index) { return index < 5 ? 'on' : 'off'; }) 
 .off { background-color: yellow; } .on { background-color: green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> </ul> 

To achieve expected result , use below option

  1. Loop div with .each
  2. Check index and addClass
  3. Exit from loop after 5th element using return false

 $('div').each(function(index) { if(index < 5){ $(this).addClass('mark') }else { return false; } }) 
 .mark{ color: red } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>1</div> <div>1</div> 

Alternatively, you can go with pure css by using .images img:nth-child(-n+5) { stuff}

.test {
  color: green;
  background: yellow;
}

.img span:nth-child(-n+3) {
  color: red !important;
  background: blue;
}
<div class="img">
  <span class="test">TEST</span>
  <span class="test">TEST</span>
  <span class="test">TEST</span>
  <span class="test">TEST</span>
  <span class="test">TEST</span>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM