Jquery: when does $ ("???") scan the entire DOM?
jQuery tries to use the fastest selection method to get what you asked for. There are a number of good resources for performance optimization tips that relate directly to jQuery:
Good ways to improve the performance of jQuery selector?
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
source to share
See function context
argument$
. If not specified, it defaults to value document
.
So, to answer your question:
$('whatever'); // scans the entire `document`
$('whatever', element); // scans only within element
source to share
How about $ (". Xxx") scans the entire DOM every time?
If you are not doing 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.
source to share
Here's a compatibility table for document.getElementsByClassName: http://www.quirksmode.org/dom/w3c_core.html#gettingelements
Green browsers for getElementsByClassName will not require a full DOM scan for $ (". ClassName") selectors and will instead use their own browser-based methods. Reds will be slower.
The difference is not as pronounced as you might think, even for thousands of items.
source to share