Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

performance - jQuery :first vs. .first()

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

The :first selector has been around since 1.0.

From the docs:

:first

The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.

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


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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If .first() and :first are used in the same context to get the same information, 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() is more performant

** enter image description here

As mentionned by Andrew Moore, .first() is the equivalent of .eq(0).
According to jsperf.com, .eq(0) would be the best, but there is no big difference with .first().

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...