cssQuery(): query the DOM with CSS selectors

Share this article

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

Frequently Asked Questions about CSS Query

What is CSS Query and how does it work?

CSS Query, also known as CSS Selector, is a powerful tool used in web development to select and manipulate HTML elements based on their id, class, type, attribute, and more. It works by applying specific styles to elements that match the specified selectors. This allows developers to create dynamic and interactive web pages with ease. CSS Query is widely used in JavaScript for DOM manipulation and in testing tools like Selenium for finding elements.

How can I use CSS Query to select elements by their attributes?

CSS Query allows you to select elements based on their attributes using square brackets []. For example, to select all elements with a specific attribute, you can use the syntax: element[attribute]. To select elements with a specific attribute value, you can use the syntax: element[attribute=”value”]. This feature is particularly useful when you want to style elements with specific attributes differently.

Can I use CSS Query to select multiple elements at once?

Yes, CSS Query allows you to select multiple elements at once using commas. For example, the syntax: h1, h2, h3 {color: red} will select all h1, h2, and h3 elements and apply the color red to them. This feature is useful when you want to apply the same style to multiple elements.

How can I use CSS Query to select child elements?

CSS Query allows you to select child elements using the > operator. For example, the syntax: div > p will select all p elements that are direct children of a div element. This feature is useful when you want to style child elements differently from their parent elements.

Can I use CSS Query to select elements based on their state?

Yes, CSS Query allows you to select elements based on their state using pseudo-classes. For example, the syntax: a:hover {color: red} will select all a elements when they are being hovered over and apply the color red to them. This feature is useful for creating interactive web pages.

How can I use CSS Query to select sibling elements?

CSS Query allows you to select sibling elements using the + operator. For example, the syntax: div + p will select all p elements that are immediately preceded by a div element. This feature is useful when you want to style elements based on their position in the HTML document.

Can I use CSS Query to select elements based on their position in the HTML document?

Yes, CSS Query allows you to select elements based on their position in the HTML document using pseudo-classes like :first-child, :last-child, and :nth-child(n). For example, the syntax: p:first-child {color: red} will select the first p element and apply the color red to it. This feature is useful for creating dynamic and interactive web pages.

How can I use CSS Query to select elements based on their type?

CSS Query allows you to select elements based on their type using the element type as the selector. For example, the syntax: p {color: red} will select all p elements and apply the color red to them. This feature is useful when you want to style all elements of a specific type in the same way.

Can I use CSS Query to select elements based on their class or id?

Yes, CSS Query allows you to select elements based on their class using the . operator and based on their id using the # operator. For example, the syntax: .class {color: red} will select all elements with the class “class” and apply the color red to them. Similarly, the syntax: #id {color: red} will select the element with the id “id” and apply the color red to it. This feature is useful when you want to style specific elements differently from others.

How can I use CSS Query to select elements that do not match a certain selector?

CSS Query allows you to select elements that do not match a certain selector using the :not() pseudo-class. For example, the syntax: p:not(.class) {color: red} will select all p elements that do not have the class “class” and apply the color red to them. This feature is useful when you want to style all elements except those that match a certain selector.

Kevin YankKevin Yank
View Author

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.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week