views:

227

answers:

5

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

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

A: 

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
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
+6  A: 

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:

http://stackoverflow.com/questions/46214/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

Ty W
+4  A: 

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
Roatin Marth
+1 such an easy thing to do, and so often forgotten
Ty W
so this is basically like doing element.find('whatever') ?
Andreas Grech
@Andreas: you are correct.
Roatin Marth
A: 

Here's a compatibility table for document.getElementsByClassName: http://www.quirksmode.org/dom/w3c%5Fcore.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
+1  A: 

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