Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery performance when selecting multiple items

This is more of a curiosity question. When doing the following:

$('.selector1, .selector2').doSomething()

Does jQuery fully traverse the DOM twice to get each set of objects matching each selector or is it finding all the elements in one traversal of the DOM?

like image 562
DA. Avatar asked Jan 25 '10 23:01

DA.


2 Answers

I think it uses the native browser functions to find this, using:

document.getElementsByClassName()
like image 102
Will Earp Avatar answered Sep 17 '22 12:09

Will Earp


It really depends on the browser. In newer browsers, it will use document.querySelectorAll for any DOM queries (under the hood this calls document.getElementsByClassName for classes). In older browsers that don't support this, then it has to figure it out on its own, which will obviously be slower.

In general, you should prefer to find stuff by id first (or at least narrow the scope). Class and tag names would be next for speed. Basically, the natively supported DOM operations are best.

like image 37
Keith Rousseau Avatar answered Sep 17 '22 12:09

Keith Rousseau