SyntaxStudy
Sign Up
jQuery jQuery .each() and Iteration
jQuery Intermediate 5 min read

jQuery .each() and Iteration

Many jQuery methods implicitly iterate over all matched elements. Sometimes, however, you need to run custom logic per element — access its index, read a specific attribute, or make a decision based on its content. The .each() method provides an explicit loop over a jQuery collection.

The Callback Signature

The callback receives two arguments: the zero-based index of the current element and the raw DOM node. Inside the callback, this refers to the DOM node; wrap it in $(this) to get the jQuery object and access jQuery methods.

Breaking Early

Return false from the callback to break out of the loop early — equivalent to break in a for loop. Return true (or anything other than false) to continue to the next iteration.

  • $(sel).each(fn) — iterate a jQuery collection
  • $.each(array, fn) — iterate any array or plain object
  • $.map(array, fn) — transform and collect results
  • return false inside callback — breaks the loop

$.each() is the utility version that works on plain arrays and objects, not just jQuery collections, making it a general-purpose iteration tool throughout your application code.

Example
// Log each item with its index
$('#results li').each(function (index, element) {
    console.log(index + ': ' + $(element).text());
});

// Set dynamic data attributes
$('table tbody tr').each(function (i) {
    $(this).attr('data-row', i + 1);
});

// Break early when a condition is met
$('input').each(function () {
    if ($(this).val() === '') {
        $(this).addClass('error');
        return false; // stop checking after first empty field
    }
});

// $.each on an object
var config = { theme: 'dark', lang: 'en', rows: 20 };
$.each(config, function (key, val) {
    console.log(key + ' = ' + val);
});
Pro Tip

Wrap "this" in $() inside .each() callbacks to access jQuery methods — "this" alone is a raw DOM node.