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.
You can put the classes in an array:
If the lists are all children of the same parent and you used
:nth-child(X)to get the element at positionX(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:But I agree with Vlad, you can easily write this directly in CSS: