Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: when does $("???") scan the whole DOM?

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

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

like image 980
flybywire Avatar asked Dec 07 '25 08:12

flybywire


2 Answers

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

like image 74
Ty W Avatar answered Dec 09 '25 22:12

Ty W


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
like image 37
Roatin Marth Avatar answered Dec 09 '25 22:12

Roatin Marth