- The Book of Dojo
- Quick Installation
- Hello World
- Debugging Tutorial
- Introduction
- Part 1: Life With Dojo
- Part 2: Dijit
- Part 3: JavaScript With Dojo and Dijit
- Part 4: Testing, Tuning and Debugging
- Part 5: DojoX
- The Dojo Book, 0.4
Selecting DOM Nodes with dojo.query
Submitted by criecke on Tue, 06/05/2007 - 18:12.
XHR is half of the Ajax story. Once you make a request for data and receive it via XHR, you must change the page - display the new data in a panel, turn an indicator from red to green, or whatever . Changing HTML is, in turn, dependent on locating nodes.
To select HTML elements in JavaScript, you can use the browser's native DOM API, but they're verbose and hard to work with...not to mention slow. For example, retrieving all nodes with the class "progressIndicator" uses this code:
var list = [];
var nodes = document.getElementsByTagName("*");
// iterate over every node in the document....SLOOOW
for(var x = 0; x < nodes.length; x++){
if(nodes[x].className == "progressIndicator"){
list.push(nodes[x]);
}
}
console.dir(list);
var nodes = document.getElementsByTagName("*");
// iterate over every node in the document....SLOOOW
for(var x = 0; x < nodes.length; x++){
if(nodes[x].className == "progressIndicator"){
list.push(nodes[x]);
}
}
console.dir(list);
Oy! That's a lot of code for what should be very simple. It's also very slow. dojo.query gives us a more compact way to do it, and it's often faster, particularly as we ask for more sophisticated kinds of relationships. The following is exactly equivalent to our first example:
console.dir( dojo.query(".progressIndicator") );
The use of CSS means you don't have to learn a whole new query language or try to manaully write out what we mean in DOM code. To top it all off, it's fast too - see the original article on dojo.query for details.
Here are some other types of queries that dojo.query will support
// portably supports most CSS 3 selectors
dojo.query(".someClassName");
dojo.query("div.someClassName");
dojo.query("tbody tr:nth-child(odd)");
dojo.query("[dojoType~=dijit]");
dojo.query("[name^=item]");
dojo.query(".someClass", "scopeId"); // scoped searches
// returns a REAL array
dojo.query(".someClassName").length;
dojo.query(".someClassName")[3];
dojo.query(".someClassName").concat(dojo.query("span"));
dojo.query(".someClassName");
dojo.query("div.someClassName");
dojo.query("tbody tr:nth-child(odd)");
dojo.query("[dojoType~=dijit]");
dojo.query("[name^=item]");
dojo.query(".someClass", "scopeId"); // scoped searches
// returns a REAL array
dojo.query(".someClassName").length;
dojo.query(".someClassName")[3];
dojo.query(".someClassName").concat(dojo.query("span"));
Read on to find out more!
- Printer-friendly version
- Login or register to post comments
- Subscribe post