jQuery / Selector / :nth-child() - 형제 요소 중 an+b번째 요소들을 선택하는 선택자
:nth-child()
는 형제 요소 중 an+b번째 요소들을 선택하는 선택자입니다.
목차
문법
$( ':nth-child(an+b)' )
a
와b
는 상수,n
은 변수입니다.n
에는 음이 아닌 정수(0, 1, 2, 3, ···)가 차례대로 대입됩니다.an+b
대신에even
,odd
를 사용할 수 있습니다.
예제
$( 'ol li:nth-child(2)' )
ol 요소의 자식 요소인 li의 형제 요소 중에서 두 번째 요소를 선택합니다.
<!doctype html> <html lang="ko"> <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)' )
n=0일 때 1, n=1일 때 3, n=2일 때 5, ···이므로, 홀수 번째 요소를 선택합니다.
$( 'ol li:nth-child(2n+1)' ).addClass( 'jb-red' );
$( 'ol li:nth-child(3n+5)' )
n=0일 때 5, n=1일 때 8, n=2일 때 11, ···이므로, 다섯 번째 요소, 여덟 번째 요소, 열한 번째 요소, ···를 선택합니다.
$( 'ol li:nth-child(3n+5)' ).addClass( 'jb-red' );
$( 'ol li:nth-child(odd/even)' )
odd는 홀수 번째 요소를, even은 짝수 번째 요소를 선택합니다.
$( 'ol li:nth-child(even)' ).addClass( 'jb-red' );
$( 'ol li.jb:nth-child(2n+1)' )
ol 요소의 자식 요소 li의 홀수 번째 요소 중에서 클래스 값으로 jb를 갖는 요소를 선택합니다. 클래스 값으로 jb를 갖는 요소 중에서 홀수 번째를 선택하는 게 아니라는 것에 주의합니다.
<!doctype html> <html lang="ko"> <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>
참고
- IE 8에서
:nth-child()
선택자를 사용하고 싶다면 jQuery 1.x 버전을 사용합니다.