JQuery: first vs. .first ()

The .first() method was added in jQuery 1.4.

The :first selector exists since 1.0.

From the docs:

:first

The :first pseudo-class :first equivalent to :eq(0) . It can also be written as :lt(1) . Although this corresponds to only one element,: :first-child can correspond to more than one: one for each parent.

.first()

Given a jQuery object representing a set of DOM elements, the .first() method creates a new jQuery object from the first matching element.




It seems that .first() is a filter that returns another jQuery object, and :first is just a selector.

But both of them can be used to achieve the same.

So when should it be used instead of another? Performance? Give examples.

+53
performance jquery
Feb 22 '10 at 17:31
source share
4 answers

.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 ); } 
+40
Feb 22 '10 at 17:38
source share

If .first() and :first are used in the same context to get the same information, for example:

Html:

 <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul> 

Script:

 console.log("1", $('ul li').first().text()); console.log("2", $('ul li:first').text()); 

.first() more efficient

** enter image description here

As Andrew Moore mentioned, .first() is the equivalent of .eq(0) .
According to jsperf.com , .eq(0) will be better, but there is not much difference with .first() .

You can see my source here: http://jsperf.com/first-vs-first-vs-eq-0

+54
Feb 07 '13 at 17:19
source share

$('li').css('color', 'red').first().css('color', 'green'); apply the filter after the collection has already been used.

In most cases, I would use the :first selector, since it can be combined with so many other good selectors , all in one sweep.

+4
Feb 22 '10 at 17:36
source share

Pseudo-selector : first and first () can do the same.

Regarding performance, here's a live example of the performance difference between jQuery first () :: first, eq (0) and: nth (0).

http://jsperf.com/jquery-first-vs-first-selector , please check this out!

Hope this helps.

+1
Jan 13 '15 at 5:01
source share



All Articles