JQuery Selector nth-child

From CoderLearner
Jump to: navigation, search

Description

Select all elements that are the nth-element of their parent. It matches with 1, even or odd, or an equation. Its index counting starts from index 1.

Syntax

$(':nth-child(even)')

$(':nth-child(odd)')

$(':nth-child(4n)')

Note

Equation: 4n, 2n, 3n,

  • 4n: 4(1),4(2),4(3),4(4), and so on
  • 2n: 2(1),2(2),2(3),2(4), and so on

Example 1

<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Select</title>
      <script 
         type="text/javascript" 
         src="/lib/jquery-1.7.2.min.js">				 
      </script>
      <style>
         .mark {
            list-style-type: none;
            border:1px solid #999900;
            width:130px;
         }
      </style>
      <script>
         $().ready(function() {
            $('ul li:nth-child(2n)').append('<span> ****</span>');
            $('tr:nth-child(odd)').css('background-color','green');
         });
      </script>
   </head>
   <body> 
      <div id="top1">
         <ul>
            <li>One</li>
            <li>Two</li>
            <li>Three</li>
            <li>Four</li>
            <li>Five</li>
            <li>Six</li>
            <li>Seven</li>
         </ul>
         <div  id="top2">
            <ul>
               <li>1</li>
               <li>2</li>
            </ul>
         </div>
      </div>
      <table border="1">
         <tr>
            <th>No</th>
            <th>Name</th>
            <th>Age</th>
         </tr>
         <tr>
            <td>1</td>
            <td>Nanak</td>
            <td></td>
         </tr>
         <tr>
            <td>2</td>
            <td>Lilo</td>
            <td></td>
         </tr>
         <tr>
            <td>3</td>
            <td>Bob</td>
            <td>14</td>
         </tr>
      </table>
      <table>
         <tr>
            <th>Group No</th>
            <th>Name</th>
            <th>Total</th>
         </tr>
         <tr>
            <td>1451</td>
            <td>Lake Group</td>
            <td>50003</td>
         </tr>
         <tr>
            <td>3451</td>
            <td>City Group</td>
            <td>5002543</td>
         </tr>
      </table>
   </body>
</html>

Try It