:first 選擇器


first 選擇器版本已棄用:3.4

說明: 選擇第一個符合的 DOM 元素。

  • 版本已新增:1.0jQuery( ":first" )

自 jQuery 3.4 起:first 偽類別已棄用。從選擇器中移除它,並使用 .first() 過濾後續的結果。

:first 偽類別等同於 :eq( 0 )。它也可以寫成 :lt( 1 )。雖然這只會匹配一個元素,:first-child 可以匹配多個:每個父元素一個。

其他注意事項

  • 由於 :first 是 jQuery 擴充套件,而非 CSS 規格的一部分,因此使用 :first 的查詢無法利用原生 DOM querySelectorAll() 方法提供的效能提升。若要使用 :first 選取元素時達到最佳效能,請先使用純 CSS 選擇器選取元素,然後使用 .filter(":first")
  • 選取的元素依其在文件中的出現順序排列。

範例

尋找第一個表格列。

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>first demo</title>
<style>
td {
color: blue;
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<table>
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
<script>
$( "tr:first" ).css( "font-style", "italic" );
</script>
</body>
</html>

示範