Monday, February 11th, 2008

Native CSS selectors with querySelector

Category: Browsers, CSS, WebKit

David Smith of WebKit posted about their native implementation of querySelector and querySelectorAll from the W3C Selectors API.

Native CSS selectors in the browsers is going to be a huge boon for us and the Ajax libraries that will be able to use them.

You can use the standard via:

javascript

  1. /*
  2.    * Get all the elements with class "hot" (duplicating getElementsByClassName)
  3.    * A common use for this is as a toggle;
  4.    * for example, a search feature might tag results with a class
  5.    */
  6.   document.querySelectorAll(".hot");
  7.  
  8.   /*
  9.    * Get the currently hovered element
  10.    */
  11.   document.querySelector(":hover");
  12.  
  13.   /*
  14.    * Get every other element in the <li> with id "large"
  15.    * This is mostly useful for doing "zebra stripe" alternating rows.
  16.    * Once CSS3 becomes more widespread, doing this directly via CSS will be more practical
  17.    */
  18.   document.querySelectorAll("#large:nth-child(even)");

Our favourite libraries can implement the same API and do the hard work in JavaScript if the browser doesn’t support it.

Point your new Webkit build at the performance test that they use (based on the mootools one) to see how fast you can be if you are native. Vroom vroom.

Posted by Dion Almaer at 7:08 am
6 Comments

++++-
4 rating from 27 votes

6 Comments »

Comments feed TrackBack URI

who will query elements 250 times without evaluating results into a cache?

Comment by Cloudream — February 11, 2008

Evaluating it 250 times is meant to avoid difference in performance due to other things happening on the system (garbage collection, other programs, etc.). If it only ran it once you may not be getting an accurate result. Plus the test would run so fast you may also encounter slight errors in the timing. Running it 250 times magnifies the results making those slight errors somewhat negligible.

Comment by Eric Anderson — February 11, 2008

It looks like your “Native” library is missing in the performance test page. Shouldn’t it be instead of dummy.js?

Comment by efattal — February 11, 2008

…and Dojo is updated to support it, although it does seem to make the nightly crash on our test pages.

http://trac.dojotoolkit.org/ticket/5832

Regards

Comment by slightlyoff — February 11, 2008

Just out of curiosity…. what does document.querySelector(“:hover”); actually return? I mean, not only can links be hovered, but also the body node … which means that you should end up with the body node whenever the mouse is inside the window. But I’ve got the strange suspicion that the result will be different….

Comment by Hans Schmucker — February 11, 2008

Ticket and patch submitted for Prototype 1.6.0.2 as well:
http://dev.rubyonrails.org/ticket/11085

Comment by jdalton — February 11, 2008

Leave a comment

You must be logged in to post a comment.