Skip to main content

cssQuery(): query the DOM with CSS selectors

By Kevin Yank

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

(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.

Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn't stop at books, he's also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!