blog

  • Home
  • blog
  • 5 jQuery.each() Function Examples

5 jQuery.each() Function Examples

This is quite an extensive overview of the jQuery each() function. This function is one of jQuery’s most important and most used functions. In this article we’ll find out why and look into its details to see how you can use it.

[author_more]

What is jQuery .each()

jQuery’s each() function is used to loop through each element of the target jQuery object. In case you’re not really experienced in jQuery, I remind you that a jQuery object is an object that contains one or more DOM elements, and exposes all jQuery functions. It’s very useful for multi-element DOM manipulation, looping arbitrary arrays, and object properties. In addition to this function, jQuery provides a helper function with the same name that can be called without having previously selected or created DOM elements. Let’s find out more in the next sections.

jQuery’s .each() Syntax

Let’s see the different modes in action.

The following example selects every div on the web page and outputs the index and the ID of each of them. A possible output is: “div0:header”, “div1:body”, “div2:footer”. This version uses jQuery’s each() function as opposed to the utility function.

[code language=”javascript”]
// DOM ELEMENTS
$(‘div’).each(function (index, value) {
console.log(‘div’ + index + ‘:’ + $(this).attr(‘id’));
});
[/code]

The next example shows the use of the utility function. In this case the object to loop over is given as the first argument. In this example I show how to loop over an array:

[code language=”javascript”]
// ARRAYS
var arr = [
‘one’,
‘two’,
‘three’,
‘four’,
‘five’
];
$.each(arr, function (index, value) {
console.log(value);

// Will stop running after “three”
return (value !== ‘three’);
});
// Outputs: one two three
[/code]

In the last example I want to present loops through the properties of an object:

[code language=”javascript”]
// OBJECTS
var obj = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5
};
$.each(obj, function (index, value) {
console.log(value);
});
// Outputs: 1 2 3 4 5
[/code]

It all boils down to provide a proper callback. The callback’s context, this, will be equal to the second argument, which is the current value. However, since the context will always be an object, primitive values have to be wrapped. Therefore, strict equality between the value and the context may not be given. The first argument is the current index, which is either a number (for arrays) or string (for objects).

Continue reading %5 jQuery.each() Function Examples%

LEAVE A REPLY