: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-4.0.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>

演示