JavaScript - - By Kevin Yank

cssQuery(): query the DOM with CSS selectors

(Via Planet Web 2.0) cssQuery(), a new JavaScript library from Dean Edwards of the IE7 script fame, sits on top of the Document Object Model (DOM) and lets you obtain references to document elements using CSS selector syntax.

The DOM is a powerful and efficient API for reading, writing and modifying HTML and XML documents. Used with JavaScript, it’s the foundation of DHTML effects. But boy can it require a lot of code sometimes.

Consider this little snippet, from a table sorting script we use here on SitePoint:

function sortables_init() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            ts_makeSortable(thisTbl);
        }
    }
}

This code is perfectly good, but really all it does is call the function ts_makeSortable on every table element with the class sortable applied to it. Here’s how the code would look with cssQuery():

function sortables_init() {
    // Find all tables with class sortable and make them sortable
    tbls = cssQuery("table.sortable");
    for (ti=0;ti<tbls.length;ti++) {
        ts_makeSortable(tbls[ti]);
    }
}

In a typical DHTML script, the code savings this can provide are staggering. Certainly, you’re giving up a little performance as your CSS selectors must be parsed and interpreted in pure JavaScript, but as yet few JavaScript applications are bringing browsers to their knees.

cssQuery() supports all CSS1 and CSS2 selectors, as well as a great many CSS3 selectors. Heck, that’s better than most current Web browsers — and it’s all written in pure JavaScript!

Update: Simon Willison produced a similar library, getElementsBySelector(), back in March 2003. It doesn’t support quite as many CSS selector types, but it probably has more than you’ll ever need in everyday use. Chances are it’s lighter as a result.