Mamadou
Mamadou

Reputation: 2307

Adding alternatively a class in <li> element of a same list in jquery

I have a list to which I would like to add 2 css class alternatively - (classOne and classTwo) in jQuery.

<ul>
<li>el 1 </li>
<li>el 2 </li>
<li>el 3 </li>
<li>el 4 </li>
<li>el n </li>
</ul>

I would like to get this

<ul>
<li class="classOne">el 1 </li>
<li class="classtwo">el 2 </li>
<li class="classOne">el 3 </li>
<li class="classTwo">el 4 </li>
<li class="classOne">el n </li>

Upvotes: 0

Views: 79

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$(function(){
    $('li:odd').addClass('classOne');
    $('li:even').addClass('classtwo');
});

Fiddle http://jsfiddle.net/DrZYQ/

Updated for better performance,

Or you can try it like,

$(function(){
    $('li').filter(':odd').addClass('classOne');
    $('li').filter(':even').addClass('classtwo');
});

Source from http://api.jquery.com/filter/

Upvotes: 3

lonesomeday
lonesomeday

Reputation: 238115

If this is for styling reasons, you don't need to use jQuery, as long as you're targeting relatively modern browsers:

li:nth-child(2n + 1) {
    /* some styles */
}
li:nth-child(2n) {
    /* some other styles */
}

If you genuinely need the classes, it's relatively easy to do with jQuery. You could do it with selectors like above, but that will probably be slower. The quickest way is probably this:

$('li').addClass(function(idx) {
    return (idx % 2 === 0) ? 'classOne' : 'classTwo';
});

Upvotes: 2

Related Questions