Good ways to improve jQuery selector performance? Good ways to improve jQuery selector performance? javascript javascript

Good ways to improve jQuery selector performance?


There is no doubt that filtering by tag name first is much faster than filtering by classname.

This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName.


In some cases, you can speed up a query by limiting its context. If you have an element reference, you can pass it as the second argument to limit the scope of the query:

$(".myclass", a_DOM_element);

should be faster than

$(".myclass");

if you already have a_DOM_element and it's significantly smaller than the whole document.


As Reid stated above jQuery is working from the bottom up. Although

that means $('#foo bar div') is a lot slower than $('bar div #foo')

That's not the point. If you had #foo you wouldn't put anything before it in the selector anyway since IDs have to be unique.

The point is:

  • if you are subselecting anything from an element with an ID then select the later first and then use .find, .children etc.: $('#foo').find('div')
  • your leftmost (first) part of the selector can be less efficient scaling to the rightmost (last) part which should be the most efficient - meaning if you don't have an ID make sure you are looking for $('div.common[slow*=Search] input.rare') rather than $('div.rare input.common[name*=slowSearch]') - since this isn't always applicable make sure to force the selector-order by splitting accordingly.