Jquery: when does $ ("???") scan the entire DOM?

When used $("#xxx")

, I think under the hoods jQuery uses getElementById

.

How about $(".xxx")

it scans the entire DOM every time?

+2


source to share


5 answers


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

+6


source


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

      

+4


source


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.

      

+1


source


Many browsers do not support getElementsByClassName

the DOM as a built-in function, so jQuery has to do the work itself, checking each element class.

0


source


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.

0


source







All Articles