views:

108

answers:

2

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?

+1  A: 

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

document.getElementsByClassName()
Will Earp
+1  A: 

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.

Keith Rousseau
It sounds like that in most every case, it's going to traverse the DOM each time for each selector. Though how it's traversing the DOM will differ based on the type of selector (element vs. ID vs. class)?
DA
Yeah, it will use a regex to split all of your queries and execute them one at a time. I wouldn't worry about performance for classes or ids, though.
Keith Rousseau