DOM Magic

By on November 1, 2009 8:01 am

Note: The Dojo Quick Start Guide posts – while still relevant – are a bit dated. Please visit http://dojotoolkit.org/documentation/ for expert tutorials and API documentation to help you get up and running with Dojo.

A really nice tool Dojo provides is dojo.query. It’s a great way to parse all or portions of the Document Object Model (DOM) and access selections of nodes. It really deserves its own book. Each of the following sections will touch on how to use dojo.query more closely, though realizing its potential is as simple as seeing it used:

dojo.require("dojo.NodeList-fx");
dojo.ready(function(){
     // our dom is ready, get the node:
     dojo.query("#testHeading")
        .addClass("testClass") // adds class="testClass"
	.fadeOut({ delay:500 }).play(); // and fade it out after 500 ms
});

Add .testClass CSS definitions to set color:red; and your heading will get that style before fading out:

.testClass {
     color:#ff0000;
}

dojo.query returns an instance of a dojo.NodeList, a synthetic super-Array of domNodes. It supports most CSS3 selectors (so you can go really wild with its syntax), and execute code against the whole list of results. To demonstrate this, we’re going to need something more than a single heading, so add some content to our DOM:

Dojo Skeleton Page

First link Second Link

First paragraph

Second paragraph

Third paragraph

And use a different query:

dojo.require("dojo.NodeList-fx");
dojo.ready(function(){
     // get each element with class="para"
     dojo.query(".para")
	.addClass("testClass")
	.fadeOut({ delay: 1000 }).play();
});

All three elements should turn red, and fade out after a second delay. The full list of things dojo.NodeList does is impressive, some of which we’ll touch on in later sections of this guide.

Most dojo.query chains have standalone functions to achieve the same goals. For instance: dojo.query(“#testHeading”).addClass(“testClass”); and dojo.addClass(“testHeading”,”testClass”) have identical results.

Other posts in the series