Grauw-lib CSS Selectors

A Javascript implementation of CSS Selectors.


DO NOT reference this file directly from your website, please host your own copy.

The code is managed in a Mercurial repository. It is available under the Apache 2.0 license. Contributions are welcome.


Typical use of CSS Selectors in JavaScript is to find all elements that match a certain selector, similar to what XPath does. This example will find all h1 elements with class name title in the document:

gl.selector.queryAll(document, 'h1.class');

Also, the implementation can match single elements against a selector, just like browsers do. This is what CSS selectors are optimised for by design, and where it stands out compared to XPath. The following example will return true if the provided element is a checkbox:

gl.selector.match(oElm, 'input[type=checkbox]');

You can see it in action in the SlickSpeed test and John Resig’s Selectors test suite.


Overall, performance is pretty good. It caches the parse trees so that a selector is only parsed the first time, and also preprocesses certain tests to increase performance.

It is also relatively easy to add optimisations that make it use browser-based XPath and CSS Selectors where possible, because of the simple object representation of the parsed selector, although it currently does not do that.

You can take a look at the SlickSpeed test for some performance comparisons, although I don’t think the testing method is very precise. Generally there does not seem to be not much performance difference between frameworks.

To minify the JavaScript code, I recommend the YUI Compressor tool. You can invoke it from the command line like this:

java -jar yuicompressor-2.4.2.jar --charset UTF-8 selector.js -o selector-compressed.js

Selector support

At the time of writing, the library supports all CSS3 Selectors, except for pseudo-element selectors and the following pseudo-class selectors: :link, :visited, :hover, :active and :focus.

The Selectors implementation is tested with a bunch of unit tests, which particularly focuses on edge cases and browser issues. Additionally, the code is used in the Backbase AJAX library which also has its own set of unit tests, covering a broader set of common cases.

Also you can run the Selectors implementation through John Resig’s Selectors test suite, where it gets a 98.7% score. The remaining 1.3% consists of lack of :hover support and wrong result order for selector groups (which is hard to implement efficiently, and not really important because I don’t actually implement the Selectors API).

Supported browsers

In principle, all browsers should be supported. Standard DOM methods are used. Specific tweaks are made for common browsers such as Firefox, Internet Explorer 6 and up, Safari and Opera. Please let me know if something doesn’t work in a certain browser (that is not ancient).

Revision history