:nth-of-type() 選擇器


nth-of-type 選擇器

說明:選取所有元素,這些元素相對於具有相同元素名稱的同層元素,是其父項的第 n 個子項。

  • 新增版本:1.9jQuery( ":nth-of-type(index/even/odd/equation)" )

    index:要比對的每個子項的索引,從 1 開始,字串 evenodd,或一個等式(例如 :nth-of-type(even):nth-of-type(4n)

由於 jQuery :nth- 選擇器的實作嚴格源自 CSS 規範,因此 n 的值是「1 開頭」,表示從 1 開始計數。對於其他選擇器表達式,例如 .first().eq(),jQuery 遵循 JavaScript 的「0 開頭」計數方式。

有關此用法的進一步說明,請參閱 W3C CSS 規格

範例

找出與其兄弟 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.jquery.com/jquery-3.7.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>

示範