Mozilla

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:

<div id="id" class="class">
    <p>First paragraph.</p>
    <p>Second paragraph.</p>
</div>

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.

18 comments

Comments are now closed.

  1. Maurício wrote on June 13th, 2009 at 16:42:

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

  2. Elijah Grey wrote on June 13th, 2009 at 17:32:

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

  3. Shawn J. Goff wrote on June 13th, 2009 at 17:33:

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

  4. Christopher Blizzard wrote on June 13th, 2009 at 17:54:

    @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!

  5. Christopher Blizzard wrote on June 13th, 2009 at 18:02:

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

  6. 蚂蚁,以用户为中心的设计 wrote on June 13th, 2009 at 19:51:

    Ant 路过

  7. William from Lagos wrote on June 14th, 2009 at 12:21:

    Good writeup John.

  8. dotnetCarpenter wrote on June 14th, 2009 at 16:52:

    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

  9. Pingback from 颠覆网络35天 ─ Firefox 3.5中DOM选取器API < MJiA on June 14th, 2009 at 22:35:

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

  10. Chris wrote on June 15th, 2009 at 06:30:

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

  11. Pingback from Guide about the new DOM document.querySelectorAll(); « Position Absolute on June 15th, 2009 at 09:18:

    […] 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 […]

  12. Pingback from Firefox 3 една година по-късно | NeXt on June 21st, 2009 at 13:59:

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

  13. Pingback from Millennium » Blog Archive » API для DOM-селекторов в Firefox 3.5 on July 7th, 2009 at 23:42:

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

  14. Pingback from 谋智社区 » Blog Archives » 颠覆网络35天 ─ Firefox 3.5中DOM选取器API on July 19th, 2009 at 17:47:

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

  15. Pingback from API selektorów w DOM w Firefoksie 3.5 « marcoos.techblog on July 28th, 2009 at 04:36:

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

  16. Trackback from Nico Steiner - Portfolio on August 8th, 2009 at 09:51:

    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…

  17. Eugene Lazutkin wrote on September 17th, 2009 at 13:32:

    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?

  18. Pingback from HTML5 selectors API – It’s like a Swiss Army Knife for the DOM | Web Directions on September 2nd, 2011 at 16:58:

    […] 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 […]

Comments are closed for this article.