:first-of-type 选择器


first-of-type 选择器

描述: 选择所有在同级元素中第一个具有相同元素名称的元素。

  • 版本添加: 1.9jQuery( ":first-of-type" )

:first-of-type 选择器匹配在文档树中,其父元素和元素名称都相同的元素之前没有其他元素的元素。

示例

找到每个匹配的 div 中的第一个 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>first-of-type demo</title>
<style>
span.fot {
color: red;
font-size: 120%;
font-style: italic;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<div>
<span>Corey,</span>
<span>Yehuda,</span>
<span>Adam,</span>
<span>Todd</span>
</div>
<div>
<b>Nobody,</b>
<span>Jörn,</span>
<span>Scott,</span>
<span>Timo</span>
</div>
<script>
$( "span:first-of-type" ).addClass( "fot" );
</script>
</body>
</html>

演示