Using Sizzle separately from jQuery

Sizzle is a crossbrowser selector engine implemented in JavaScript and used in the popular jQuery library.

In modern browsers, Sizzle utilizes standard DOM methods querySelectorAll() and matchesSelector(), providing high performance. In old browsers as well as for nonstandard selectors, pure-script implementation is used — it is slower, but provides compatibility even with IE6/7.

A nice feature of Sizzle is that it’s standalone and can be used without jQuery if advanced features of jQuery are unneeded for a specific task or project. This can result in speedup of loading: with minification and Gzip compression used, Sizzle’s size is just 6 KB (!) — which is more than 5 times less than size of jQuery under similar conditions.

Using Sizzle is as simple as using jQuery:

var elements = Sizzle('.example > LI');

Result of this will be a standard JavaScript array (Array object) of elements that match the specified selector.

As in jQuery, an optional second argument can be a context element to search descendant elements in (by default, context is entire HTML document — document object):

var context  = document.getElementById('some-container');
var elements = Sizzle('.example > LI', context);

There is also an optional third argument that can be an existing array, which selected elements will automatically be added to:

var spans = Sizzle('SPAN');
var elems = Sizzle('DIV', document, spans);
// Now, `spans` and `elems` variables contain the same array
// of same `SPAN` and `DIV` elements.

Additionally, Sizzle provides two another useful functions providing jQuery.filter()-like functionality:

Sizzle.matchesSelector(element, selector)
Determines if an element matches a selector. Returns a boolean value (true or false).
Sizzle.matches(selector, elements)
Returns a JavaScript array of those elements from a specified array that match a specified selector.