In the last post, we looked at using dojo.query()
to select elements on the page. In this post, I’ll show how to process each element in the NodeList returned from dojo.query()
.
NodeList Methods
There are a number of methods available to process dojo NodeLists, but most of them are very similar to JavaScript array processing methods, so I won’t go into detail here.
Take a look at the dojo documentation for more information.
dojo.forEach()
The method I want to focus on is dojo.forEach()
, because it can be used to process a NodeList that you select with using dojo.query()
Since dojo.query()
returns a NodeList, you can just tack on the forEach()
method to process it in the same statement. This is the syntax:
dojo.query('someQuery').forEach(function(node, index) { logic here... });
The forEach()
method takes an anonymous callback function to process each node. That function will automatically receive parameters for the individual node and index number of that node being processed. The parameter names don’t matter and you don’t have to specify them at all if you don’t need to use them (although you generally want to at least have a handle to the node).
Here’s an example of getting a handle to all fields on the page and printing their values (and index number) to the console:
dojo.query('input').forEach(function(node, index) { console.log(index + ': ' + node.value); });
Here’s an example of automatically setting the value of each field on the page:
dojo.query('input').forEach(function(node, index) { node.value = 'This is field ' + i; });
Here is the result:
Up Next
Now that we know how to locate the elements we want to target and process the NodeList, we’ve got a great foundation to build upon. In the next few posts, we’ll look at more ways to manipulate elements on the page.
