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,032
  • 3
  • 41
  • 65
flybywire
  • 247,088
  • 187
  • 391
  • 495

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,504
  • 4
  • 27
  • 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
  • 111,976
  • 25
  • 153
  • 138
Roatin Marth
  • 22,517
  • 3
  • 48
  • 54
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,430
  • 11
  • 80
  • 108
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
  • 138,842
  • 31
  • 279
  • 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
  • 58,451
  • 13
  • 115
  • 134