Thursday, October 02, 2008

W3C Selectors API

CSS Selectors have been a slick way of finding elements in the DOM. Something as simple as the following would select all the td tags that are children of a tbody tag within an table with the id of "score" and set the background color to gray.


<style>
#score>tbody>tr>td { background: gray; }
</style>

The selectors syntax for CSS 2.1 is simply described below:

Picture 1.png
Until I became familiar with JQuery, I had been ignorant of the fact that the syntax I've been using for CSS styles would be a fantastic way to get things out of the DOM from Javascript.

Now, the W3C standards body is introducing a selector API that will be available in both IE 8 and Firefox 3.1. So the following syntax will do the same selection as above, except available in javascript:

var cells = document.querySelectorAll("#score>tbody>tr>td");

The W3C draft says that all objects that implement Document, DocumentFragment and Element interfaces, must now also implement the NodeSelector interface.

The NodeSelector interface is defined as follows:

interface NodeSelector {
Element querySelector(DOMString selectors);
NodeList querySelectorAll(DOMString selectors);
};

Pretty cool stuff.

Of course, with every step towards a common implementation across browsers, there's awlays a catch. The selectors syntax is different between CSS 2.1 and CSS 3. And of course IE has decided to use CSS 2.1 selector syntax, and Firefox is using CSS 3. So, you'll probably want to make sure you write for CSS 2.1. Below is a summary of differences:

  • the list of basic definitions (selector, group of selectors, simple selector, etc.) has been changed; in particular, what was referred to in CSS2 as a simple selector is now called a sequence of simple selectors, and the term "simple selector" is now used for the components of this sequence

  • an optional namespace component is now allowed in type element selectors, the universal selector and attribute selectors

  • a new combinator has been introduced

  • new simple selectors including substring matching attribute selectors, and new pseudo-classes

  • new pseudo-elements, and introduction of the "::" convention for pseudo-elements

  • the grammar has been rewritten

  • profiles to be added to specifications integrating Selectors and defining the set of selectors which is actually supported by each specification

  • Selectors are now a CSS3 Module and an independent specification; other specifications can now refer to this document independently of CSS

  • the specification now has its own test suite

0 comments: