2

When using $("#xxx") I guess under the hoods jQuery uses getElementById.

What about $(".xxx") does it scan the whole DOM every time?

Samir Talwar
  • 14,220
  • 3
  • 41
  • 65
flybywire
  • 261,858
  • 191
  • 397
  • 503

5 Answers5

6

jQuery attempts to use the fastest selection method to get what you asked for. There are a number of good resources with performance optimization tips out there that relate directly to jQuery:

Good ways to improve jQuery selector performance?

http://www.artzstudio.com/2009/04/jquery-performance-rules/

http://www.componenthouse.com/article-19

http://www.learningjquery.com/2006/12/quick-tip-optimizing-dom-traversal

Community
  • 1
  • 1
Ty W
  • 6,694
  • 4
  • 28
  • 36
4

See the context argument to the $ function. If not supplied, it defaults to the entire document.

So to answer your question:

$('whatever'); // scans the entire `document`

$('whatever', element); // scans only within element
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
Roatin Marth
  • 23,589
  • 3
  • 51
  • 55
1

What about $(".xxx") does it scan the whole DOM every time?

If you don't do the caching: yes. Caching is simple enough:

var $myCachedElements = $('.myElements'); // DOM querying occurs

$myCachedElements.animate({left: '1000px'}, 'slow'); // no DOM Querying this time, as long as you use the variable.
pixeline
  • 17,669
  • 12
  • 84
  • 109
0

Many browsers do not support getElementsByClassName as a native DOM function, so jQuery has to do the work itself by checking each element's classes.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • But it does try to use any Selector API method before gEBCN last I recall? Then the lowest common denominator is looping through each elements clsas. – meder omuraliev Sep 23 '09 at 18:40
0

Here's a compatibility table for document.getElementsByClassName: http://www.quirksmode.org/dom/w3c_core.html#gettingelements

The browsers in green for getElementsByClassName will not require a full DOM scan for $(".className") selectors, and will use browser-native methods instead. The ones in red will be slower.

The difference isn't as pronounced as you'd think though, even for thousands of elements.

Dave Ward
  • 59,815
  • 13
  • 117
  • 134