jQuery API

.first()

.first() Returns: jQuery

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

  • version added: 1.4.first()

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

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>
<head>
  <style>.highlight{background-color: yellow}</style>
  <script src="http://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:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .first() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • koreanchang
    Example,,,
    $("p span:first-child").addClass('highlight');
  • darcnite
    i'd say it's a simpler way of doing .get(0)
  • No, it's just another way of doing .eq(0).
  • Bill
    A better example would be helpful as the description doesn't distinguish the benefits over using eq(0) and :first.
  • Tim
    Got a question..

    Is calling .first() faster than using the selector ':first'?
  • moltendorf
    Using .first() is about ten times faster than using :first. Tested using Firefox 3.6.

    100,000 iterations:
    55,870ms using :first
    5,858ms using .first()

    Code:
    $(document).ready (function() {
    var i, time = +new Date;
    for ( i = 0; i < 100000; ++i ) {
    $ ( 'div:first' );
    }
    console.log ( (+new Date) - time );
    time = +new Date;
    for ( i = 0; i < 100000; ++i ) {
    $ ( 'div' ).first ( );
    }
    console.log ( (+new Date) - time );
    });
  • Richard Coles
    i think its much faster cause it doesn't require selector parsing