jQuery performance when selecting multiple items
Asked Answered
C

2

9

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?

Chen answered 25/1, 2010 at 23:11 Comment(4)
I Dont think so because from what ive seen in core the matches are done on with regex on various node properties (nodeName, NodeType, id, etc.) So any single selector produces one iteration of the DOM. However, Im not 100% positive on this so i will defer to others more familar with the internals :-)Resplendent
actually the example is bad because <selector2> node does not exist in HTML :)Hydrophilous
I think what you want to do is seek out the selector engine, Sizzle, whose source code you can look at: github.com/jeresig/sizzle github.com/jeresig/sizzle/blob/master/sizzle.jsFayalite
@KARASZI 'doh! Foiled by a typo! I'll fix that. ;o)Chen
W
1

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

document.getElementsByClassName()
Windmill answered 26/1, 2010 at 15:16 Comment(0)
W
1

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.

Widely answered 26/1, 2010 at 17:59 Comment(2)
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)?Chen
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.Widely

© 2022 - 2024 — McMap. All rights reserved.