Reputation: 41595
I have been taking a look on some sites and they all talk about using tag selectors instead of classes to improve the performance.
For example, this:
$("input.myclass");
Instead of this:
$(".myclass");
For example:
They all claimed that JavaScript only had getElementById
and getElementsbyTagName
and not a way to select classes directly.
Has this changed in the last 3 years? Are they now able to select by class? I was testing it with jsperf and it seems the class selector is faster by far: http://jsperf.com/class-vs-input
I also took a look at other's people testings and show the same results: http://jsperf.com/selectors-perf/3
Has this changed in these last year? Should we now select by class rather than by tags? Where can I take a look at the browsers' versions implementing natively the class selector?
Thanks.
Upvotes: 1
Views: 298
Reputation: 590
It has changed now.
Most of the browsers are implementing :
var matches = document.body.querySelectorAll('div.highlighted > p');
Inside their implementation in javascript.
That's what jQuery uses inside now; It is implementing sizzle.js, a selector js library that chooses whether to use querySelector or the regular getElementsByTagName function;
For example, for the jquery constructor function $()
if the first argumemt is a string : $(iAmAString)
,
then if the first letter of the string is a #
, jquery will call document.getElementById(iAmAString.substr(0))
.
If not it will let sizzle handle whether calling querySelector depending on the browser's compatibility and the complexity of the string.
and lots of other awesome things.
Being the most precise when selecting your element, using base functions and caching your frequently used selectors, will reduce the number of checks when passing through this big chain and/or even circumvent the whole chain.
For some websites, this had the particular effect of generating a unicorn riding kitten effect of awesomeness, what more to say:
the compatibiity support is here https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelectorAll
Upvotes: 2