First off, welcome to inetpub, my foray into the world of blogging at work. Part of my job is working with web standards and non-standards, so I figured that I could share my knowledge with whomever wants to listen.

One of the biggest and most useful up and coming browser features is the introduction of the W3C Selectors API. This handy set of functions lets you use CSS selectors in your DOM code to get a collection of elements with exceptional specificity. For example:

var elms = document.querySelectorsAll(".cssClass");

will get you a collection of elements with the CSS class "cssClass" applied on it. Now, you might ask why we need this if there's document.getElementsByClassName(). Well, for starters, getElementsByClassName is non-standard which means that only Firefox and a handful of other browsers support it. Furthermore, IE adds support for the Selectors API in version 8 which makes this a standardized, cross-browser method of grabbing all elements with a given class.

It gets better though: You can query for any valid CSS selector, for example:

var elms = document.querySelectors("#navbar li.selected");

gets you the selected nav node in the nav bar element. You can even query for siblings and direct descendants using the + and > selection operators, respectively. Also note the two methods presented above are different: The first one, querySelectorsAll, will get a collection of all elements on the page that match the given selector. The second method, querySelectors, will get the first element on the page that matches the selector.

You can also run these methods on an element to get children of a given node, for example:

var contentArea = document.getElementById("contentArea");
var codeSections = contentArea.querySelectorsAll("pre.code");

The beauty of these methods is that they're already natively supported in almost every browser. The rendering engine must use the same operations to apply the CSS styles to the page in the first place. This API provides you, the web developer, with a direct link into the ultra-performant rendering core of the browser.

You can read more about the Selectors API on the W3C's Selectors API homepage.