Niranjan Borawake
Niranjan Borawake

Reputation: 1638

In what order are jQuery selectors executed?

If I have following jQuery selector specified :

$("div#myDivId .myClass")

What is the exact selection order? Will this first select a div with an ID myDivId and then find all elements with myClass inside it or first select all elements with myClass and then filter out rest which are not inside myDivId.

Upvotes: 4

Views: 1453

Answers (1)

Eugene D. Gubenkov
Eugene D. Gubenkov

Reputation: 5357

Sizzle API (that used by jQuery) uses "right-to-left" order of selector's tokens "execution".

For the modern browsers that support QSA (native querySelectorAll function) Sizzle will actually delegate the work to it that also "right-to-left".

Here is performance comparison: Sizzle vs. QSA, also I've create sample for your case: http://jsperf.com/does-order-of-selectros-matters

Another question is why they are "right-to-left"? See here: https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left

Upvotes: 5

Related Questions