简体   繁体   中英

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.

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):

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM