hacks.mozilla.org

Author Archive for John Resig

DOM Traversal in Firefox 3.5

Firefox 3.5 includes new support for two W3C DOM traversal specifications. The first, the Element Traversal API, focuses on making element-by-element traversal easier, the second, the NodeIterator interface which makes finding all node types much easier.

Element Traversal API

The purpose of the Element Traversal API is to make it easier for developers to traverse through DOM elements without having to worry about intermediary text nodes, comment nodes, etc. This has long been a bane of web developers, in particular, with cases like document.documentElement.firstChild yielding different results depending on the whitespace structure of a document.

The Element Traversal API introduces a number of new DOM node properties which can make this traversing much simpler.

Here’s a full break-down of the existing DOM node properties and their new counterparts:

Purpose All DOM Nodes Just DOM Elements
First .firstChild .firstElementChild
Last .lastChild .lastElementChild
Previous .previousSibling .previousElementSibling
Next .nextSibling .nextElementSibling
Length .childNodes.length .childElementCount

These properties provide a fairly simple addition to the DOM specification (and, honestly, they’re something that should’ve been in the specification to begin with).

There is one property that is conspicuously absent, though: .childElements (as a counterpart to .childNodes). This property (which contained a live NodeSet of the child elements of the DOM element) was in previous iterations of the specification but it seems to have gone on the cutting room floor at some point in the interim.

But all is not lost. Right now Internet Explorer, Opera, and Safari all support a .children property which provides a super-set of the functionality that was supposed to have been made possible by .childElements. When support for the Element Traversal API was finally landed for Firefox 3.5, support for .children was included. This means that every major browser now supports this property (far in advance of all browsers supporting the rest of the true Element Traversal specification).

Some examples of the Element Traversal API (and .children) in action:

Show next element when a click occurs:

someElement.addEventListener("click", function(){
    this.nextSiblingElement.style.display = "block";
}, false);

Add classes to all of the child elements:

for ( var i = 0; i < someElement.children.length; i++ ) {
    someElement.children[ i ].className = "active";
}

NodeIterator API

NodeIterator is a relatively old API that hasn’t seen wide adoption, and has just been implemented in Firefox 3.5. Specifically, the NodeIterator API is designed to allow for easy traversal of all nodes in a DOM document (this includes text nodes, comments, etc.).

The API itself is rather convoluted (containing a number of features that aren’t immediately important to most developers) but if you wish to use it for some simpler tasks it be quite easy.

The API works by creating a NodeIterator (using document.createNodeIterator) and passing in a series of filters. The NodeIterator is capable of returning all nodes in a document (or within the context of a given node) thus you’ll want to filter it down to only show the ones that you desire. A simple example of this can be found below.

Construct a NodeIterator for iterating through all the comment nodes in a document.

var nodeIterator = document.createNodeIterator(
    document,
    NodeFilter.SHOW_COMMENT,
    null,
    false
);
 
var node;
 
while ( (node = nodeIterator.nextNode()) ) {
    node.parentNode.removeChild( node );
}

Once constructed the NodeIterator is bi-directional (you can move in any direction, using previousNode or nextNode).

Perhaps the best use of the API is in traversing over commonly-used (but difficult to traverse) nodes like comments and text nodes. Since there already exist a few APIs for traversing DOM elements (such as getElementsByTagName) this does come as a welcomed respite to the normal means of node traversal.

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.