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

<script>
$(document).ready(function(){
$('#cl li:nth-child(2)').css('color', 'red');    
})
</script>

      

Html

<ul id="cl">
  <li>home</li>
  <li>home2</li>
  <li>home3</li>
  <li>home4</li>
  <li>home5</li>
  <li>home6</li>
</ul>

      

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 :)

+3


source to share


2 answers


Using the selector :odd

:

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

      

http://api.jquery.com/odd-selector/

Here's the Jsfiddle:

http://jsfiddle.net/uKX3t/1/



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 )

+8


source


Try this instead -



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

      

+1


source







All Articles