Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to use selectors in jQuery?

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.

like image 541
Webnet Avatar asked Jan 17 '11 19:01

Webnet


People also ask

Which jQuery selector is fastest?

HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.

Which selector is faster in JavaScript?

Specifically, getElementById() and getElementsByClassName() are more than twice as fast as querySelector() and querySelectorAll() .

Can we use multiple selectors in jQuery?

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.


2 Answers

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
like image 52
user113716 Avatar answered Oct 02 '22 02:10

user113716


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:

  • Speed is variable on FF, sometimes GC turns on 'div.active' test, but generally difference is very small.
  • Unnoticable difference on Chrome and Safari
  • Faster on IE9
like image 26
gertas Avatar answered Oct 02 '22 03:10

gertas