Reputation: 7305
I have classes with different values in them and i want to add those classes to set elements in order.
This is supposed to be just an explanation of what im looking for:
<div class="These">Lorem ipsum</div>
<div class="These">Lorem ipsum</div>
<div class="These">Lorem ipsum</div>
$('.These').each(function() {
var TheseINDEX = $(this).index();
$(this).addClass('first, second, third');
});
Result:
<div class="These first">Lorem ipsum</div>
<div class="These second">Lorem ipsum</div>
<div class="These third">Lorem ipsum</div>
Not like that abomination above was perfect but theres another thing.. I'm also thinking that it would be cool if that would loop.
Lets say i have 3 classes just like before and those 3 classes would be added to 8 elements
Result would be this:
<div class="These first">Lorem ipsum</div> <!-- #1 -->
<div class="These second">Lorem ipsum</div>
<div class="These third">Lorem ipsum</div>
<div class="These first">Lorem ipsum</div>
<div class="These second">Lorem ipsum</div>
<div class="These third">Lorem ipsum</div>
<div class="These first">Lorem ipsum</div>
<div class="These second">Lorem ipsum</div> <!-- #8 -->
as in it would keep adding these preset classes until theres no ".These" for them to be added to. This looping would work much like a backup incase you run out of classes...
http://jsfiddle.net/Z4PAZ/ - jsfiddle of my example..
Any ideas?
Upvotes: 0
Views: 1987
Reputation: 340055
var classes = ['first', 'second', 'third'];
$('.These').each(function(i, el) {
$(this).addClass(classes[i % classes.length]);
});
or, more simply (and efficiently):
var classes = ['first', 'second', 'third'];
$('.These').addClass(function(i, c) {
return classes[i % classes.length];
});
In particular, this version requires only one function call per element, whereas the original required three (i.e. the callback, the $(this)
constructor, and addClass
).
Upvotes: 5
Reputation: 12581
If you store the different CSS class names in an array, you can use modula arithmetic to get the one you want based on the index of the element. Also, the each
function provides a parameter which is the index of that element so you don't need to recalculate it with $(this).index();
var arrCssClasses = ['first', 'second', 'third'];
$('.These').each(function(idx) {
//var TheseINDEX = $(this).index();
$(this).addClass(arrCssClasses[idx%arrCssClasses.length]);
});
Upvotes: 1
Reputation: 78750
var classes=["first","second","third"];
$('.These').each(function(i) {
$(this).addClass(classes[i%classes.length]);
});
Upvotes: 5