.first()


.first()返回: jQuery

描述: 获取匹配元素集合中第一个元素。

  • 添加的版本: 1.4.first()

    • 这个方法不接受任何参数。

如果一个jQuery对象表示一个DOM元素的集合,.first()方法会构造一个新的jQuery对象,它包含了前一个集合的第一个元素。

考虑一个页面上的一个简单的列表:

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

我们可以应用此方法设置列表项:

1
$('li').first().css('background-color', 'red');

调用的结果是第一个列表项目为红色背景。

例子:

高亮段落中的第一个span 。

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<style>.highlight{background-color: yellow}</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
<script>$("p span").first().addClass('highlight');</script>
</body>
</html>

Demo: