1. Jan 18th, 2006

    Prototype adds CSS selectors

    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.

    1. Apr 1st, 2006

      Dan Kubb

      Hi Assaf,

      I used assert_tag for the first time this week and I have to agree that the interface is a little clumsy and un-ruby-like.

      Any chance you’ll submit a patch to rails, or package up a library for your CSS selector based assert_tag method?

    2. Apr 1st, 2006

      Assaf

      I want to submit it as a patch for Rails, I think it’s useful to enough people that it belongs in the core Rails, not as a separate download. I just can’t find the time to do it. I could definitely use help with that.

    3. Jun 25th, 2006

      sylvinus

      I’ve written a 20x speedup patch for the $$ function, with interactive test suite, I hope you’ll find it useful and leave me a comment on it !

      http://www.sylvainzimmer.com/index.php/archives/2006/06/25/speeding-up-prototypes-selector/

      Thanks :)

    Your comment, here ⇓

    Or using OpenID