jQuery Snippit – .each()

Here at Switch On The Code we love us some jQuery. We not only have tutorials, but we use jQuery ourselves for the very site you are visiting right now. It makes the life of a web developer so much easier. Sometimes, however, there just isn’t a magical jQuery function that does what you need. On occasion you need to select a bunch of stuff and do some custom logic on each element. You don’t necessarily need to move all the objects or change some css, sometimes you just need to do something more your own style. This is where the each() function comes in.

The each() works just like it sounds. It takes a collection of jQuery objects and iterates over each DOM object for the jQuery objects. This is an important fact to remember, that each() iterates the DOM objects associated with the jQuery objects, not the jQuery objects themselves. Now, that being said, it is not difficult to use each. First, we have to start with some HTML to manipulate.

<div id="numbers">
  <span>45</span>
  <span>10</span>
  <span>35</span>
  <span>89</span>
  <span>17</span>
</div>

So here we have a few numbers inside a div. Let’s say we want to add 10 to every number. jQuery doesn’t have a function to do that, which is not too much of a surprise. However, using jQuery’s each(), it becomes much easier.

$(‘#numbers span’).each(function(index)
{
  var num = parseInt($(this).text());
  num = num + 10;
  $(this).text(num);
});

With this simple example we just select all the spans inside the div, convert the text to an int, then finally add ten and set the span text to the new number. With jQuery’s each() it is extremely quick and quite simple to do. We just have to remember that the function iterates DOM objects so this refers to a DOM object, not a jQuery Object. This is why you see $(this) which converts the DOM object into a jQuery object.

This is it for this snippit, and now you know how the each() works. If you have any questions concerning jQuery or javascript, just head over to the forums. And don’t forget, when you need coding help, all you have to do is Switch On The Code.

Leave a Reply

Your email address will not be published. Required fields are marked *