开发者

Most efficient jQuery selectors

开发者 https://www.devze.com 2023-04-08 18:18 出处:网络
Which of the following selectors is most efficient in jQuery? Or is there any real difference? input[type=text]

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 开发者_如何学Pythonthe 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):

Most efficient jQuery selectors


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号