Take the 2-minute tour ×

I recently started working with jQuery and was wondering how I would iterate through a collection (an array or list of items) of items and sum their contents.

Does jQuery have something like a for-loop like many other languages do?

Would there be an easy way to implement this - if this isn't easily do-able?

share|improve this question
add comment

3 Answers

up vote 14 down vote accepted

What you are looking for is the jQuery .each() function - which will allow you to iterate through any given field(s) and perform an action. Here are some examples to get you started (just as simple arrays - check documentation for additional functionality):


var array = [ "stack", "overflow"];

$.each(array, function() {
      //Perform actions here (this) will be your current item

Example: (Summing an array of numbers - alerting the sum)

var sum = 0;

$.each(array, function() {
      sum += (this);

share|improve this answer
add comment

$.each(function) and $(...).each(function) both accurately perform the equivalent of a for-each loop, but the actual JavaScript for-each equivalent is the for(... in ...) loop.

for (variable in object)
    // code to be executed


This isn't jQuery-specific, but hey, jQuery is just a JavaScript library after all. :)

share|improve this answer
And this spares memory which can be useful on mobile devices. Why doesn't Apple the simply make an IPHONE WITH 4 GB RAM! D:< –  user142019 Jan 5 '11 at 21:29
add comment

For an array, see Rionmonster's answer. For all items matchins a selector:

$("a").each(function() {
share|improve this answer
add comment

Your Answer

