Main Tutorials

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.


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

<body>

<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>
</table>
<br/>

<button>:nth-child(4)</button>
<button>:nth-child(3n)</button>
<button>:nth-child(even)</button>    
<button>:nth-child(odd)</button>


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

</body>
</html>

About Author

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

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
samy
4 years ago

I tried the demo, it is ok, i tried the html it won’t work using any browser.

samy
4 years ago
Reply to  samy

i downloaded jqeury code and saved it into a text document and saved it into my working folder, then made reference to this .js into your html nice example, now it works. thank a lot

Karl
11 years ago

Really nicely/functional presented examples.