.first()

.first()

.first()Returns: jQuery

Description: Reduce the set of matched elements to the first in the set.

  • version added: 1.4.first()

    • This method does not accept any arguments.

Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first element in that set.

Consider a page with a simple list on it:

<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>

We can apply this method to the set of list items:

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

The result of this call is a red background for the first item.

Example:

Highlight the first span in a paragraph.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>first demo</title>
  <style>
  .highlight{
    background-color: yellow
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js" rel="external nofollow" ></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:

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/first

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部