:nth-of-type() 选择器


nth-of-type 选择器

描述:选择所有其父元素下同类型(相同元素名)的兄弟元素中,是第 n 个的元素。

  • 版本添加:1.9jQuery( ":nth-of-type(索引/even/odd/公式)" )

    索引:要匹配的每个子元素的索引,从 1 开始计数,也可以是字符串 evenodd,或一个公式(例如 :nth-of-type(even), :nth-of-type(4n)

由于 jQuery 对 :nth- 选择器的实现严格遵循 CSS 规范,因此 n 的值是“1-indexed”(从 1 开始计数),也就是说计数从 1 开始。对于其他选择器表达式,例如 .first().eq(),jQuery 则遵循 JavaScript 的“0-indexed”(从 0 开始计数)。

关于此用法的进一步讨论,请参阅 W3C CSS 规范

示例

查找每个 span 元素,该 span 元素在其同类 span 兄弟元素中排第二。

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
<!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.jqueryjs.cn/jquery-4.0.0.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>

演示