.first() can be used to select the first item in the jQuery collection.
In principle, it avoids the need to fulfill a new request or break the chain in situations where you need to work with the collection, and then exclusively on the first element.
In fact, one of the most expensive operations you can do in jQuery is the query. The less you do, the better ...
An example is the image gallery of the script, where your first image is always active by default, but you need to attach an event handler to each image ...
$('#gallery img').click(myFunc).first().addClass('active'); // Instead of $('#gallery img').click(myFunc); $('#gallery img:first').addClass('active');
.first() also syntactic sugar for something that exists with 1.1.2 ... .eq(0) :
$('#gallery img').click(myFunc).eq(0).addClass('active');
actually, as implemented in jQuery itself:
first: function() { return this.eq( 0 ); }
Andrew Moore Feb 22 '10 at 17:38 2010-02-22 17:38
source share