The .first() method was added in jQuery 1.4.
The :first selector has been around since 1.0.
From the docs:
The
:firstpseudo-class is equivalent to:eq(0). It could also be written as:lt(1). While this matches only a single element,:first-childcan match more than one: One for each parent.Given a jQuery object that represents a set of DOM elements, the
.first()method constructs a new jQuery object from the first matching element.
It seems that .first() is a filter that returns another jQuery object, while :first is just a selector.
But, they can both be used to accomplish the same thing.
So, when should one be used instead of the other? Performance? Please provide examples.
.first()can be used to select the first element in a jQuery collection.Basically, it avoids having to do a new query or break the chain in situations when you need to work on a collection and then exclusively on the first element.
Actually, one of the most costly operations you can do in jQuery is a query. The less you do, the better it is…
One example I can think of right now is an image gallery script where your first image is always the default active one, yet you need to attach an event handler on each image…
.first()is also syntactic sugar for something that exists since 1.1.2….eq(0):in fact, that’s how it is implemented in jQuery itself: