Numbered child (:nth-child(n/even/odd/expr))

Description and Syntax

$(':nth-child(n/even/odd/expr)')

selects all elements that are the nth child of their parent.

Examples

SelectorSelects
$('li:nth-child(2)')all <li> elements that are the second child of their parent
$('p:nth-child(odd)')all <p> elements that are an odd-numbered child of their parent (first, third, fifth, and so on)
$('.myclass:nth-child(3n+2)')all elements with the class myclass that are the (3n+2)th child of their parent (second, fifth, eighth, and so on)

Given the following HTML code:


<div>/*from   ww w .  jav a2s.com*/
 <h2></h2>
 <p></p>
 <h2></h2>
 <p></p>
 <p></p>
</div>
  • $('p:nth(1)') selects the second <p> because numbering for :nth(n) starts with 0
  • $('p:nth-child(1)') selects nothing because there is no <p> element that is the first child of its parent
  • $('p:nth(2)') selects the third <p>
  • $('p:nth-child(2)') selects the first <p> because it is the second child of its parent

:nth-child(n) can take even or odd.

For


<div>// ww  w .  j  a  va 2  s .c om
 <h2></h2>
 <p></p>
 <h2></h2>
 <p></p>
 <p></p>
</div>

$('p:nth-child(even)') selects the first and third <p> because they are children 2 and 4 (both even numbers) of their parent.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  ww w .  ja v  a2 s.  c o m-->
                $("ul li:nth-child(2)").append("<span> - 2nd!</span>");
        });
    </script>
  </head>
  <body>
    <body>
      <div>
        <ul>
            <li>A</li>
            <li>B</li>
            <li>C</li>
        </ul>
      </div>
      <div>
        <ul>
            <li>D</li>
            <li>E</li>
            <li>F</li>
            <li>G</li>
            
        </ul>
      </div>
      <div>
        <ul>
            <li>H</li>
            <li>I</li>
            <li>J</li>
            <li>K</li>
        </ul>
      </div>

    </body>
</html>

Click to view the demo

The code above generates the following result.

Numbered child (:nth-child(n/even/odd/expr))