A selector may result in more than one element being referenced. For instance doing $("div") would result in a reference to ALL DIVs on the page being found. If we wanted to set the text on all the DIVs to a common value we might do something like this:
$("div").text("this is a div");
This will apply the text() method to all the elements our selector has matched. In this case, all the DIVs. This is a very handy feature, though sometimes we need to do further processing on each of the matched elements. We could set up a loop and use the underlying array of elements, but jQuery provides us with an easier way - the each() method. Let's imagine that we had 10 DIVs that contained numbers, and we need a way to calculat the sum of all those numbers. We could make use of the each() method for this.
var total = 0;
$("div.theNumbers").each( function () {
total = total + parseFloat( $(this).text() );
});
alert(total);
The magic here is the each() method. It takes a function as it's parameter and that function is executed for each of the elements matched by our selector. Additionally, the position of the element in our list is passed to the function as a parameter. If we need to make use of this position detail, then we just need to provide a parameter name (i.e. function (pos) ). For our sample problem we don't need the position so have just ignored it.
Because the function is executed for each of our matching elements, we can make use of the this keyword. Within our function, this will refer to the current DOM element. So by saying $(this), we indicate we want the jQuery object for the currently mactched item. From there we can grab the text contained in the item via the .text() method. In our sample this text should be a number, however the .text() method will return a string representation of the number to us. So we extract the numeric value via the parseFloat function (which is a native JavaScript function). The above code would work fine if we had 2 or 200,000 DIVs on the page - as long as they each had the "theNumbers" class.