When using $("#xxx")
I guess under the hoods jQuery uses getElementById
.
What about $(".xxx")
does it scan the whole DOM every time?
When using $("#xxx")
I guess under the hoods jQuery uses getElementById
.
What about $(".xxx")
does it scan the whole DOM every time?
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.
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
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
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.
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.