:nth-of-type() selector

Selects all elements that are the nth child of their parent in relation to siblings with the same element name.

Because jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as :eq() or :even jQuery follows JavaScript's "0-indexed" counting.

Further discussion of this usage can be found in the W3C CSS specification.

jQuery( ":nth-of-type(index/even/odd/equation)" )
version added: 1.9
Examples:

Find each span that is second in relation to its sibling spans.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>nth-of-type demo</title>
  <style>
  .nth {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>
  <span>John</span>,
  <b>Kim</b>,
  <span>Adam</span>,
  <b>Rafael</b>,
  <span>Oleg</span>
</div>
<div>
  <b>Dave</b>,
  <span>Ann</span>
</div>
<div>
  <i><span>Maurice</span></i>,
  <span>Richard</span>,
  <span>Ralph</span>,
  <span>Jason</span>
</div>
 
<script>
$( "span:nth-of-type(2)" )
  .append( "<span> is 2nd sibling span</span>" )
  .addClass( "nth" );
</script>
 
</body>
</html>
doc_jQuery
2016-03-27 13:48:51
Comments
Leave a Comment

Please login to continue.