:first-of-type 选择器

first-of-type selector

描述:选择所有的属于相同元素名称的同辈元素第一个的元素。

  • 增补版本: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-1.10.2.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>

演示: