Reputation: 997
I've created a list and am trying to add a different class name to each one. Currently, I'm using this method:
HTML:
<ul class="sd-list">
<li><a href="#">List Item 1</a></li>
<li><a href="#">List Item 2</a></li>
<li><a href="#">List Item 3</a></li>
</ul>
jQuery:
$('.sd-list:nth-child(1)').addClass('green');
$('.sd-list:nth-child(2)').addClass('red');
$('.sd-list:nth-child(3)').addClass('purple');
This works fine, but I'm wondering if there is a better method than the one I'm currently using. Any help would be greatly appreciated.
Upvotes: 1
Views: 5530
Reputation: 4212
$(function () {
$(".sd-list li").each(function(index) {
$(this).attr("class", "color" + index);
});
});
Upvotes: 1
Reputation: 816324
You can put the classes in an array:
var colors = ['green', 'red', 'purple'];
$('.sd-list').each(function() {
var index = $(this).index();
if (index < colors.length) {
$(this).addClass(colors[index]);
}
});
If the lists are all children of the same parent and you used :nth-child(X)
to get the element at position X
(instead of truly using it as "the n-th child of parent"), and you have a class for each position, you can also simplify it to:
$('.sd-list').addClass(function(index) {
return colors[index];
});
But I agree with Vlad, you can easily write this directly in CSS:
.sd-list:nth-child(1) {
/* rules */
}
/* etc */
Upvotes: 4