Just the weekly tutorials.

Using "each" to Loop Through a List of Selected Elements

Before we dive in, let's identify the distinction between the $.each method and $(selector).each method. They are different.

The $(selector).each method, described in this tutorial, take a CSS selector to work with. That is, a list of HTML elements. But the main $.each method(another tutorial), is a slightly different function.

  • $(selector).each is attached to the prototype object. It only works on CSS selectors represented by a jQuery object only (it will not work with regular objects, however it does work with arrays, for example. But this is not mentioned in jQuery documentation.) This is the method that is explained in this tutorial.
  • $.each method is attached directly to the main jQuery object. It works on selectors, however, the CSS selector needs to be passed directly to the method as the first parameter. It also works with JSON objects, plain JavaScript objects and Arrays. With regard to its location within the jQuery object, its definition can be written as $.fn.each or $.prototype.each (jQuery renames "prototype" object (which already exists in JavaScript in all JavaScript object constructors, including the jQuery object) to "fn".

The main difference is that $(selector).each cannot work on data types other than elements selected. $.each can work (loop through) another data type such as an Array, not just HTML elements.

Do you ever need to loop through a list of similar HTML elements and modify them in a certain way? Use "each" method that loops through a list of elements previously selected using a CSS selector. The following listing describes HTML we will be working with in this tutorial:

<div> <p>In a not so distant future. That happened in the past.</p> <p>There was once upon a time a man. Who at first was last.</p> <p>There was something thrown at something. Something fell apart.</p> <p>There were only three things left. Water, blood and heart.</p> </div>

The CSS selector "div p" will scan the web page for all paragraph tags that are nested within "div" tags. Just as shown in the HTML above. Then, an anonymous function is used here, to administer any JavaScript statement to all selected elements. In this case, the blue color is applied to each paragraph.

// Select elements var elements = $("div p"); // Go through the list of selected elements elements.each( function() { this.style.color = "blue"; } );

This button selects all paragraphs on this page using the selector $("p") and colors them all red,
in a way similar to the source code above, except the color is different.

That was a simple example of using each. What if we want to capture the index of each element as we loop through them? The anonymous function can also have two parameters.

In the following example, function() was replaced with function(index, js_obj) to show that we can track index and have a reference to the JavaScript object through other means than the "this" variable, although within the each loop they will refer to the same object:

$("p").each(function(index, js_obj) { // js_obj refers to the same object as "this" js_obj.style.color = "blue"; // Convert the JavaScript element object to a jQuery object $(js_obj).append(" index = " + index); });

First, the function colors a paragraph in blue color. Then new HTML text is appended to the end of the paragraph, indicating its index which was passed through the nameless function through variable "index".

Appending text to the very end of an HTML tag (but still within it) is done using jQuery's $(selector).append method. And, alternatively, $(selector).prepend can be used to add HTML text to the very beginning of an HTML tag, within it.

$(selector).each and Arrays

Although jQuery documentation says that $(selector).each works with jQuery objects only, it will still properly work with an object of type Array. In this case the parameters of the nameless function will equate to the values of "index" and "value" stored at that index.

var arr = [0,5,7]; $(arr).each(function(index, value) { var i = index; // 0,1,2 var v = value; // 0,5,7 // do something });

Notice the following precautions.

We cannot pass an object to the $(selector).each method. Although this code will not produce a syntax error and execute, it will not parse the object properly, because this version of each method is not intended to be used with JavaScript objects, but rather jQuery objects only (and Arrays as witnessed above.)

var obj = {"a":"1","b":"2"};
$(obj).each(function(index, value) { /* ... */ });

Instead, this can be achieved using the main $.each method:

var obj = {"a":"1","b":"2"};
$.each(obj, function(index, value) { /* ... */ });

Now it works.

Just the weekly tutorials.