Selectors can be used in jQuery to match a set of elements in a document. Most CSS selectors are implemented, as well as a set of custom ones.
The jquery core includes a DOM element selections engine named sizzle which traverses the DOM. The current version of Sizzle is v2.3.3. Sizzle has influenced the architecture of other Javascript frameworks such as yui v3 and dojo and motivated the creation of the standard selectors-api.
A complete list of supported selectors is available at jQuery's API documentation: Selectors. Most CSS selectors are implemented, as well as a set of custom ones.
Examples of valid selectors include $(".className")
, $("#idName")
, and $("div.className:not('#idName'))
.
Optimizing jQuery
Cache
var that = $(this);
that.find("div");
Cache your selectors by storing it to a variable if your going to use the same selector more than once so you don't avoid repeating selectors. Doing this keeps jQuery from having to search the entire DOM every time you call the selector.
Use ID-based selectors
//slow
$( ".redbox" );
//better
$( "#container div.redbox" );
// Fast!
$( "#container" ).find( "div.redbox" );
.find() is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.
Specificity
// slow
$( "div.data .redrow" );
// Fast!
$( ".data td.redrow" );
Be specific on the right-hand side of your selector, and less specific on the left. Use tag.class if possible on your right-most selector, and just tag or just .class on the left.
A "flatter" DOM also helps improve selector performance, as the selector engine has fewer layers to traverse when looking for an element.
Universal Selector
// slow
$( ".robot > *" );
// better
$( ".robot" ).children();
// Implied universal selection. (slow!)
$( ".redform :radio" );
// Same thing, explicit now. (better)
$( ".redform *:radio" );
// Fast!
$( ".redform input:radio" );
Chaining
// slow
$( "#box" ).hide();
$( "#box" ).show();
// fast
var box = $( "#box" );
box.hide().show();
Instead of selecting the same thing multiple times for multiple methods, just have one selector with all the methods you needs chained onto it. Almost every jQuery method returns the object it was using. Doing this keeps searches and variable accesses to a minimum.
Direct descenders
// slow
$('body h1')
$('body').find('h1')
// faster
$('body > h1')
$('body').children('h1')
Use direct-descendant operators whenever possible.
HTML5
If you can, use HTML5. HTML5 creates new page layout elements like section, header, footer, article, etc.. Having more specific layout tags means there are less items that share a given tag name, which translates into better selectors.