Donald T
Donald T

Reputation: 10637

Most efficient jQuery selectors

Which of the following selectors is most efficient in jQuery? Or is there any real difference?

  1. input[type=text]
  2. [type=text]
  3. input:text
  4. :text

Of course, an ID selector on the element would be best because the interpreter can use getElementById(), but I'm trying to understand the general differences in the above selectors.

Upvotes: 1

Views: 496

Answers (2)

James Allardice
James Allardice

Reputation: 165951

Here's a quick test case I set up (note that I've added the necessary quotes around the attribute name selectors). It looks like the first method is fastest, which is expected really (because the others imply a universal * selector), followed by [type='text'], and in last place is :text.

In reality, the difference is so minimal it doesn't really matter which you choose.

Here's a screenshot (edit - I've added in the 4th method after seeing the update to the question):

enter image description here

Upvotes: 5

Daff
Daff

Reputation: 44205

Breaking it down:

input[type=text]
// and
[type=text]

Are both attribute selectors. The first one being faster because the lookup of the attribute is already narrowed down to input elements.

input:text
:text

Are jQuery extensions. From the :text selector docs:

Because :text is a jQuery extension and not part of the CSS specification, queries using :text cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use [type="text"] instead.

So these selectors are slower (whereas narrowing it down to input elements will be faster here as well).

Upvotes: 1

Related Questions