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");
Tags :
Founder of, 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.
My website is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts