nth-child selector
Description: Selects all elements that are the nth-child of their parent.
-
version added: 1.1.4jQuery( ":nth-child(index/even/odd/equation)" )
index: The index of each child to match, starting with
1
, the stringeven
orodd
, or an equation ( eg.:nth-child(even)
,:nth-child(4n)
)
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. jQuery methods like .first()
or .eq()
jQuery follows JavaScript's "0-indexed" counting. Given a single <ul>
containing two <li>
s, $( "li:nth-child(1)" )
selects the first <li>
while $( "li" ).eq( 1 )
selects the second.
The :nth-child(n)
pseudo-class is easily confused with the .eq( n )
call, even though the two can result in dramatically different matched elements. With :nth-child(n)
, all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With the .eq( n )
call only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.
Further discussion of this unusual usage can be found in the W3C CSS specification.
Examples:
Find the second li in each matched ul and note it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
|
Demo:
This is a playground to see how the selector works with different strings. Notice that this is different from the even
and odd
which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
|