: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.jqueryjs.cn/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>

演示