From Ajaxian:
Example: Find all elements inside elements with class “summaryâ€, all inside the with id “page†and hide each matched tag:
$$('div#page p.summary img').each(Element.hide);
I discovered the multiple uses of CSS selectors when I bumped into behaviour. After playing with it for a while, I learned CSS selectors are extremely handy for selecting HTML elements based on their attributes. They’re easier to write than XPath expressions. Well, most of the time. They’re concise, readable and have a zero learning curve for Web developers.
A while back I implemented CSS selectors for the Ruby Microformat parser. Microformats are all about finding semantic data in HTML. CSS selectors are all about identifying these semantics. Want to find an event? Use .event. Try writing that in XPath.
Then, last night I played with Rails functional tests. I wrote a test case to verify a form contains an input field for the username. Rails has an assert_tag function just for that. Can you guess what this means?
assert_tag :tag=>"input",
:attributes=>{ :type=>"text", :name=>"username", :maxlength=>32
:ancestor=>{ :tag=>"form",
:ancestor=>{ :tag=>"div", :attributes=>{ :class=>"login" } }
}
It’s Ruby, but it’s certainly not concise, readable or fun to write. It just looks … wrong.
So I pulled the Ruby Microformat parser library, and rewrote the same test using CSS selectors:
assert_tag "div.login form input[type=text][name=username][maxlength=32]"
Coupled with the new prototype library, I can now use CSS selectors to style pages, add JavaScript goodness, parse HTML, and write test cases.
Like last year’s AJAX, CSS selectors are the best kept secret that’s making a comeback.
Update: It must be CSS day. Here’s another good post, this time, on how not to write CSS.