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

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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.

Comments

  • Pingback: Blue Coaster33()

  • http://www.curvecables.asia Karl

    Really nicely/functional presented examples.