728x90
SMALL
#jQuery
#:nth-child()
:nth-child()
:nth-child() is a selector that selects the an+bth sibling element.
grammar
$( ':nth-child(an+b)' )
- a and b are constants, n is a variable.
- Non-negative integers (0, 1, 2, 3, ...) are assigned to n in sequence.
- You can use even, odd instead of an+b.
example
$( 'ol li:nth-child(2)' )
Selects the second element from the sibling elements of li, which is a child element of the ol element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<style>
.jb-red { color: red; }
</style>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
jQuery( document ).ready( function() {
$( 'ol li:nth-child(2)' ).addClass( 'jb-red' );
} );
</script>
</head>
<body>
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
<li>Nine</li>
<li>Ten</li>
</ol>
</body>
</html>
$( 'ol li:nth-child(2n+1)' )
1 when n=0, 3 when n=1, 5 when n=2, and so on, so select the odd-numbered element.
$( 'ol li:nth-child(2n+1)' ).addClass( 'jb-red' );
$( 'ol li:nth-child(3n+5)' )
5 when n = 0, 8 when n = 1, 11 when n = 2, etc. So select the 5th element, the 8th element, the 10th element, and so on.
$( 'ol li:nth-child(3n+5)' ).addClass( 'jb-red' );
$( 'ol li:nth-child(odd/even)' )
odd selects odd elements, even selects even elements.
$( 'ol li:nth-child(even)' ).addClass( 'jb-red' );
$( 'ol li.jb:nth-child(2n+1)' )
Selects elements with jb as the class value from the odd-numbered elements of the child element li of the ol element. Note that it does not select the odd numbered element among those that have jb as the class value.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<style>
.jb-red { color: red; }
</style>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
jQuery( document ).ready( function() {
$( 'ol li.jb:nth-child(2n+1)' ).addClass( 'jb-red' );
} );
</script>
</head>
<body>
<ol>
<li>One</li>
<li class="jb">Two</li>
<li class="jb">Three</li>
<li class="jb">Four</li>
<li class="jb">Five</li>
<li class="jb">Six</li>
<li class="jb">Seven</li>
<li class="jb">Eight</li>
<li class="jb">Nine</li>
<li class="jb">Ten</li>
</ol>
</body>
</html>
Reference
In IE 8, if you want to use the :nth-child() selector, use the jQuery 1.x version.
728x90
LIST