jQuery: $.each() example and syntax

The jQuery's $.each() utility function is an iterator that can perform operations on several types of JavaScript collections, including objects, arrays and DOM collections. This function is global, in the sense that it doesn't belong to the jQuery's selector chain (such as its namesake, .each()) and can operate at any scope level inside your jQuery code. To understand how this function works, you first need to understand its syntax, which is as follows:

$.each(collection, function(index, value) {

  // ...

});

where collection is the JavaScript or jQuery collection you want to iterate over, index is the numeric index of each collection's member (or the name of the properties and methods in case of JavaScript objects) and value is the current value of each item within the collection.

Let's start with an object such as the following:

// Object

var Class = {
  
   property: 'Property',
   method: function() {
     alert('Method');
   }
};

We can use $.each() as follows:

$.each(Class, function(member, value) {
  
    if(typeof value !== 'function') {
    
      alert(value);
    
    
    } else {
    
      value();
    
    }
  
  
});

The above code will alert first 'Property' and then 'Method'. As you can see, we've passed the name of the object as the first parameter of $.each() and then we've used the anonymous callback function to iterate over the object itself. In case of objects, member is the name of the property or method of the object and value is the actual member. In our example, we simply check if a member of the Class object is a method or not and we perform an action accordingly.

Now we can use arrays:

// Array

var collection = [1, 'a', true, null];

We can use $.each() as follows:

$.each(collection, function(index, value) {
  
    alert(index + ' is ' + value);
  
  
});

In this case, index corresponds to the numerical index of each array's item and value to the actual item's value. The above code will simply output '0 is 1, 1 is a...' and so on.

Finally, $.each() can also iterate over DOM collections. For example:

// NodeList

var nodeList = document.getElementsByTagName('li');

We can use $.each() as follows:

$.each(nodeList, function(index, node) {
  
  alert('Node ' + index + ' is a ' + node.nodeName +  
        ' and contains ' + node.firstChild.nodeValue);
  
  
});

In this case, instead, index corresponds to the numerical index of the DOM collection and node to each DOM node in the collection. The above code will simply alert the numerical index of a node, its HTML name and its contents.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.