DOM selectors API in Firefox 3.5

The Selectors API recommendation, published by the W3C, is a relatively new effort that gives JavaScript developers the ability to find DOM elements on a page using CSS selectors. This single API takes the complicated process of traversing and selecting elements from the DOM and unifies it under a simple unified interface.

Out of all the recent work to come out of the standards process this is one of the better-supported efforts across all browsers: Usable today in Internet Explorer 8, Chrome, and Safari and arriving in Firefox 3.5 and Opera 10.

Using querySelectorAll

The Selectors API provides two methods on all DOM documents, elements, and fragments: querySelector and querySelectorAll. The methods work virtually identically, they both accept a CSS selector and return the resulting DOM elements (the exception being that querySelector only returns the first element).

For example, given the following HTML snippet:

First paragraph.

Second paragraph.

We would be able to use querySelectorAll to make the background of all the paragraphs, inside the div with the ID of ‘id’, red.

var p = document.querySelectorAll("#id p");
for ( var i = 0; i < p.length; i++ ) {
    p[i].style.backgroundColor = "red";
}

Or we could find the first child paragraph of a div that has a class of 'class' and give it a class name of 'first'.

document.querySelector("div.class > p:first-child")
    .className = "first";

Normally these types of traversals would be very tedious in long-form JavaScript/DOM code, taking up multiple lines and queries each.

While the actual use of the Selectors API methods is relatively simple (each taking a single argument) the challenging part comes in when choosing which CSS selectors to use. The Selectors API taps in to the native CSS selectors provided by the browser, for use in styling elements with CSS. For most browsers (Firefox, Safari, Chrome, and Opera) this means that you have access to the full gamut of CSS 3 selectors. Internet Explorer 8 provides a more-limited subset that encompasses CSS 2 selectors (which are still terribly useful).

The biggest hurdle, for most new users to the Selectors API, is determining which CSS selectors are appropriate for selecting the elements that you desire - especially since most developers who write cross-browser code only have significant experience with a limited subset of fully-working CSS 1 selectors.

While the CSS 2 and CSS 3 selector specifications can serve as a good start for learning more about what's available to you there also exist a number of useful guides for learning more:

Implementations in the Wild

The most compelling use case of the Selectors API is not its direct use by web developers, but its use by 3rd-party libraries that already provide DOM CSS selector functionality. The trickiest problem towards adopting the use of the Selectors API, today, is that it isn't available in all browsers that users develop for (this includes IE 6, IE 7 and Firefox 3). Thus, until those browsers are no longer used, we must use some intermediary utility to recreate the full DOM CSS selector experience.

Thankfully, a number of libraries already exist that provide an API compatible with the Selectors API (in fact, much of the inspiration for the Selectors API comes from the existence of these libraries in the first place). Additionally, many of these implementations already use the Selectors API behind the scenes. This means that you can use using DOM CSS selectors in all browsers that you support AND get the benefit of faster performance from the native Selectors API implementation, with no work to you.

Some existing implementations that gracefully use the new Selectors API are:

It's important to emphasize the large leap in performance that you'll gain from using this new API (in comparison to the traditional mix of DOM and JavaScript that you must employ). You can really see the difference when you look at the improvement that occurred when JavaScript libraries began to implement the new Selectors API.

When some tests were run previously the results were as follows:

You can see the dramatic increase in performance that occurred once the libraries began using the native Selectors API implementations - it's quite likely that this performance increase will happen in your applications, as well.

Test Suite

To coincide with the definition of the Selectors API specification a Selectors API test suite was created by John Resig of Mozilla. This test suite can be used as a way to determine the quality of the respective Selectors API implementations in the major browsers.

The current results for the browsers that support the API are:

  • Firefox 3.5: 99.3%
  • Safari 4: 99.3%
  • Chrome 2: 99.3%
  • Opera 10b1: 97.5%
  • Internet Explorer 8: 47.4%

Internet Explorer 8, as mentioned before, is missing most CSS 3 selectors - thus failing most of the associated tests.

As it stands, the Selectors API should serve as a simple, and fast, way of selecting DOM elements on a page. It's already benefiting those who use JavaScript libraries that provide similar functionality so feel free to dig in today and give the API a try.

About John Resig

More articles by John Resig…


18 comments

  1. Maurício

    Please, review the 3th block of code under the heading “Using querySelectAll”. Shouldn’t it be > instead of <?

    June 13th, 2009 at 16:42

  2. Elijah Grey

    For WP-Syntax, don’t forget to put escaped="true" on the <pre/> tags containing syntax-highlighted code or markup.

    June 13th, 2009 at 17:32

  3. Shawn J. Goff

    Looks like the code syntax highlighter is messing with your character entities in the Javascript samples.

    June 13th, 2009 at 17:33

  4. Christopher Blizzard

    @Elijah – that’s actually a problem that I just fixed (again) with WP stripping out certain things based on roles – should be fixed now. Sorry about that!

    June 13th, 2009 at 17:54

  5. Christopher Blizzard

    @Maurício – Yep, you’re right! (I blame Resig! :D) I’ve fixed the example and thanks!

    June 13th, 2009 at 18:02

  6. 蚂蚁,以用户为中心的设计

    Ant 路过

    June 13th, 2009 at 19:51

  7. William from Lagos

    Good writeup John.

    June 14th, 2009 at 12:21

  8. dotnetCarpenter

    Hmm.. I get 58.5%: 1265 passed, 899 failed in IE8 (v. 8.0.6001.18783) and not 47.4%. Has the test been improved or did you guys use another version of IE8?

    Cheers, Jon

    June 14th, 2009 at 16:52

  9. […] 原文地址:DOM selectors API in Firefox 3.5 系列地址:颠覆网络35天 […]

    June 14th, 2009 at 22:35

  10. Chris

    IE8 you fail me again. Great stats, the speed difference is sick!

    June 15th, 2009 at 06:30

  11. […] Resig wrote a good piece on the new querySelectorAll.all() api on hacks.mozzila.org. document.querySelectorAll() give you a better grip on CSS selection. For exemple, if you want to […]

    June 15th, 2009 at 09:18

  12. […] браузъри вече имат html5 благини като <canvas>/<video>/Selector API/Storage/Data […]

    June 21st, 2009 at 13:59

  13. […] ниже расположен перевод заметки DOM selectors API in Firefox 3.5 с John Resig (автора jQuery равным образом евангелиста […]

    July 7th, 2009 at 23:42

  14. […] 原文地址:DOM selectors API in Firefox 3.5 系列地址:颠覆网络35天 […]

    July 19th, 2009 at 17:47

  15. […] serii tłumaczeń artykułów z bloga Mozilla Hacks, przedstawiam dzisiaj tłumaczenie artykułu DOM Selectors API in Firefox 3.5 autorstwa Johna […]

    July 28th, 2009 at 04:36

  16. Ladies and Gentlemen, please welcome……

    Semantic Checker!

    Nachdem ich die halbe Nacht durchprogrammiert habe, ist die erste Version meiner zweiten Firefox-Extension Semantic Checker fertig und bei den Mozilla Firefox Add-ons veröffentlicht.

    Die Extension kann mit einem Klick über die…

    August 8th, 2009 at 09:51

  17. Eugene Lazutkin

    Dojo 1.0.2 and Dojo 1.1.1? Really? Dojo 1.0.2 was released on 2/15/2008, Dojo 1.1.1 was released on 5/12/2008 — more than a year ago. Why didn’t you use Dojo 1.3.1 available for download since April 2009?

    September 17th, 2009 at 13:32

  18. […] API at Opera Developers Center, by Lachlan Hunt, one of the authors of the spec.Selectors API at Mozilla HacksThoughts on performance from JS performance guru Nicholas Zakas (the comments are well worth […]

    September 2nd, 2011 at 16:58

Comments are closed for this article.