Reputation: 25
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
add class to first 5 element from every 10. have many Divs
Upvotes: 2
Views: 3011
Reputation: 3940
Just determine what the last digit is, and if less than 5, add class. Could be one line in the function but I assigned a variable for readability.
$('div').each(function(i){
var num = parseInt(i.slice(-1));
$(this).toggleClass('cube', num < 5);
});
Upvotes: 0
Reputation: 51
You can use jQuery
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$().ready(function(){
var counter = 0;
$(".cube").each(function(idx,obj)
{
counter++;
if(counter <= 5 )
{
$(obj).addClass('newstyle');
}
if(counter == 10) counter = 0;
})
});
</script>
Upvotes: 0
Reputation: 122057
This is CSS approach using nth-child
pseudo-class
ul {
list-style-type: decimal;
}
li:nth-child(10n+1),
li:nth-child(10n+2),
li:nth-child(10n+3),
li:nth-child(10n+4),
li:nth-child(10n+5){
background: green;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Upvotes: 2
Reputation: 12173
I think this is a pretty nice approach using jQuery
// Loops through each cube element
$('.cube').each(function(index) {
// Gets the last integer in the index (ie. 0-9)
var num = (index + 1) % 10;
// If 1,2,3,4 or 5
if (num <= 5 && num > 0)
// Add the new class
$(this).addClass('newClass');
});
Here is a full example
$('.cube').each(function(index) {
var num = (index + 1) % 10;
if (num <= 5 && num > 0)
$(this).text('new cube');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
<div class="cube">cube</div>
Upvotes: 2
Reputation: 66560
Try:
var counter = 0;
$('.cube').each(function(i) {
if (i % 10 == 0) {
counter = 1;
} else {
counter++;
}
if (counter < 5) {
$(this).addClass('something');
}
});
Upvotes: 0
Reputation: 3375
Using javascript, use a two counter, one for every 10 divs and another for the first 5 divs and with jquery addClass
, it is easy.
Upvotes: -1