How to apply css for every second child using nth-child () with jquery

Hi I want to apply the style on every second <li>

I tried

$('#cl li:nth-child(2)').css('color', 'red');    



<ul id="cl">


I can only apply the style to the second child using this code. how can i apply the style for every second child

Thanks in advance :)


source to share

2 answers

Using the selector :odd


$('#cl li:odd').css('color', 'red');

Here's the Jsfiddle:

The reason you need to use :odd

as opposed to :even

is because children are indexed 0, which means that it <li>home</li>

is the 0th child and <li>home2</li>

is the first child that is odd.

Quote from docs:

In particular, note that 0-based indexing means that, counter-intuitively,: odd selects the second element, the fourth element, etc. within the agreed set.

Funnily enough, you need to use a selector odd

(pun intended )



Try this instead -

$('#cl li:odd').css('color', 'red');




All Articles