: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.jquery.com/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>

示範