jQuery – nth-child selector example

The jQuery nth-child is used to select all elements that are ntg-child of of their parent. The nth-child(n) is “1-indexed”, meaning the “n” is counting starts at 1.

For example,
1. $(‘tr:nth-child(3)’) – selects all elements matched by <tr> that are the third child of their parent.
2. $(‘tr:nth-child(3n)’) – selects all elements matched by <tr> that are every third child of their parent.
3. $(‘tr:nth-child(even)’) – selects all elements matched by <tr> that are the even child of their parent.

P.S The ‘even’ and ‘odd’ are always used to create table zebra stripes effect.

jQuery Example

A simple example to demonstrate the use of the nth-child function to change the table row background color dynamically.

<title>jQuery nth-child example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>


<h1>jQuery nth-child example</h1>

<table border=1>
	<tr><td>Row #1</td></tr>
	<tr><td>Row #2</td></tr>
	<tr><td>Row #3</td></tr>
	<tr><td>Row #4</td></tr>
	<tr><td>Row #5</td></tr>
	<tr><td>Row #6</td></tr>
	<tr><td>Row #7</td></tr>
	<tr><td>Row #8</td></tr>
	<tr><td>Row #9</td></tr>
	<tr><td>Row #10</td></tr>


<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("tr").css("background", "white");
      $("tr" + str).css("background", "coral");


About the Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.


1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Karl Recent comment authors
newest oldest most voted

Really nicely/functional presented examples.