Which is faster: input[type="checkbox"] or :checkbox?
So which should I use to select elements? I'm using checkbox as just an example, this question refers to all form elements开发者_运维技巧.
Actually while we are at it, which of these are faster:
li:first
or
li:eq(0)
?
From the documentation:
Although, semantically:
$(':checkbox')
is equivalent to$('[type=checkbox]')
practically speaking:
Because
:checkbox
is a jQuery extension and not part of the CSS specification, queries using:checkbox
cannot take advantage of the performance boost provided by the native DOMquerySelectorAll()
method. For better performance in modern browsers, use[type="checkbox"]
instead.
Always read the documentation. It will make your life easier, and ours.
You can see the performance difference for yourself in this testcase.
In the browsers tested so far, :checkbox
is a lot slower.
For the second part of your question: using :first
or :eq(0)
doesn't seem to make much difference.
Different browsers are implemented differently. It will be impossible to choose an answer that is true for all of them. Different sized pages might even change the answer. You need to test your code for performance problems, and fix the ones you find. It's extremely unlikely that the difference between these simple selectors will be a problem.
精彩评论