jQuery each() and map()

When you need to do something different for each element of a selection, or loop over an array or an object, use each(). For many tasks you do not need a loop, because jQuery methods work on all selected elements, but when you need it, it is simple.

$(selector).each()

<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>
$('li').each(function (index, element) {
  console.log(index + ': ' + $(element).text());
});
Console output

0: Apple
1: Banana
2: Cherry

  • index is the position, starting from 0.
  • element is the DOM element. Inside the function, this is the same element.

Break and continue

Return false to stop the loop (like break). Return true (or just return) to go to the next item (like continue).

$('li').each(function (i) {
  if (i === 0) return true;            // skip the first
  if ($(this).text() === 'Cherry') return false;   // stop here
  console.log($(this).text());
});
Console output

Banana

$.each() for arrays and objects

<p>Page</p>
var colors = ['red', 'green', 'blue'];
$.each(colors, function (i, value) {
  console.log(i + ' = ' + value);
});

var user = { name: 'Anita', city: 'Delhi' };
$.each(user, function (key, value) {
  console.log(key + ': ' + value);
});
Console output

0 = red
1 = green
2 = blue
name: Anita
city: Delhi

map(): make a new array from the elements

.map() runs a function for each element and collects the returned values. Add .get() to change the jQuery object into a normal array.

<ul>
  <li data-price="10">Pen</li>
  <li data-price="25">Book</li>
  <li data-price="5">Eraser</li>
</ul>
var names = $('li').map(function () {
  return $(this).text();
}).get();
console.log(names);

var prices = $('li').map(function () {
  return $(this).data('price');
}).get();
console.log(prices);

var total = prices.reduce(function (sum, p) { return sum + p; }, 0);
console.log('Total: ' + total);
Console output

[ 'Pen', 'Book', 'Eraser' ]
[ 10, 25, 5 ]
Total: 40

$.map() and $.grep()

var numbers = [1, 2, 3, 4, 5, 6];
console.log($.map(numbers, function (n) { return n * 2; }));
console.log($.grep(numbers, function (n) { return n % 2 === 0; }));
Console output

[ 2, 4, 6, 8, 10, 12 ]
[ 2, 4, 6 ]

Native alternatives

Modern JavaScript has forEach, map and filter for arrays, and they are the better choice for pure arrays. Use the jQuery methods for jQuery selections.

var numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.map(function (n) { return n * 2; }));
console.log(numbers.filter(function (n) { return n % 2 === 0; }));
Console output

[ 2, 4, 6, 8, 10, 12 ]
[ 2, 4, 6 ]

Note: Do not change the list (add or remove items) while you loop over it. Next: jQuery load().

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.