If I have a CSS class which I only ever apply to form elements, eg:
<form class="myForm">
Which of these two jQuery selectors is most efficient, and why?
a) $('form.myForm')
b) $('.myForm')
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As redsquare already mentioned, the selection algorithm changed in later jQuery versions (partly due to getElementsByClassName support). Additionally, I tested this with the most recent jQuery version to date (v1.6) and also added a test for document.getElementsByClassName for comparison (works at least in Firefox 4 and Chrome).
The results in Firefox 4 were:
The accepted answer is outdated (and is still found by searching for something like “efficient way to find elements in jquery”) and can mislead people, so I felt that I have to write this.
Also, take a look at the time difference between jQuery and native browser selector functions. In jQuery 1.2.6
$('.myForm')was more than 300 times slower thangetElementsByClassName, while in jQuery 1.6 it was only about 20 times slower, but still faster than$('form.myForm')(contrary to the outdated answer).Note: The results were obtained with Firefox 4 (similar results with Chrome). In Opera 10 querying with tag name is only slightly faster, but Opera also supports the much faster native
getElementsByClassName.Test code: http://jsbin.com/ijeku5