The jQuery nth-child selector is a selector that is used to select specific elements from a group of elements. The selector is derived directly from the CSS specification, but is browser independent so you can use it in browsers that don't support CSS 3. This article will cover the basics of using nth-child. Let's get started.

Selecting Even/Odd Elements

Let's say you have a group of divs:


<div class="even">
	<div>Me</div>
	<div>You</div>
	<div>It</div>
	<div>We</div>
	<div>They</div>
	<div>He</div>
	<div>She</div>
</div>

You can easily zebra stripe every other div by doing this:


$(".even div:nth-child(even)").css("background-color", "#eee");

Doing so results in the all of the even rows being zebra striped like this:

Me
You
It
We
They
He
She

You can instead stripe all of the odd rows by doing this:


$(".odd div:nth-child(odd)").css("background-color", "#eee");

Doing so will result in all of the odd rows being selected:

Me
You
It
We
They
He
She

Selecting Every N Elements

What if you only wanted to zebra stripe every 3rd element? That's easy as well. Given that you have a group of divs that look like this:


<div class="multiples">
	<div>Me</div>
	<div>You</div>
	<div>It</div>
	<div>We</div>
	<div>They</div>
	<div>He</div>
	<div>She</div>
	<div>Boy</div>
	<div>Girl</div>
	<div>Apple</div>
	<div>Orange</div>
	<div>Banana</div>
	<div>Strawberry</div>
</div>

You can quite easily highlight every n element (in this case, every 4th element) by doing this:


$(".multiples div:nth-child(4n)").css("background-color", "#eee");

Which will then result in this:

Me
You
It
We
They
He
She
Boy
Girl
Apple
Orange
Banana
Strawberry

Selecting a Single Element

Finally, what if we wish to select a single element from a group, with no repeats? Given we have a set of elements that look like this:


<div class="specific">
	<div>Me</div>
	<div>You</div>
	<div>It</div>
	<div>We</div>
	<div>They</div>
	<div>He</div>
	<div>She</div>
</div>

We can do this to select a specific element (in this case, the 3rd one):


$(".specific div:nth-child(3)").css("background-color", "#eee");

So that the result looks like this:

Me
You
It
We
They
He
She


Please note that we used zebra striping as an example for this article, but you can do anything, including attach event listeners, etc. That's it! Thanks for reading!