is it more efficient to use $('.active')
or $('div.active')
? I have always avoided including "div" because it's extra text in the javascript file I don't want the user to have to download.
HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.
Specifically, getElementById() and getElementsByClassName() are more than twice as fast as querySelector() and querySelectorAll() .
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
Older versions of IE will benefit from the inclusion of div
because they don't support getElementsByClassName()
.
Because of that, every element on the page needs to be selected with:
document.getElementsByTagName('*');
...and manually tested to see if it has the active
class.
If you include div
, then it is able to narrow it down a bit, since it can do:
document.getElementsByTagName('div');
...then test only those elements.
When I say older versions, I mean IE6 and IE7 since IE8+ supports querySelectorAll
.
EDIT:
Browser suppport:
getElementsByClassName
: http://www.quirksmode.org/dom/w3c_core.html#t11
querySelectorAll
: http://www.quirksmode.org/dom/w3c_core.html#t13
It depends. If you mean performance.
I prepared special test for everyone on JSPerf: jquery class selector test.
On my browser and computer (FF 3.6.13 and Core 2 Duo 1.6) div.active
is a bit slower. But found it variable - it seems GC has something doing here.
And after few more tests it seems that div.active
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With