38

I am working on trying to better understand the jQuery.each() method. Here's an example I came up with, not very practical, but it performs an action on each selected item from the selected set of elements returned:

// Loop over each link.
$( "#links a.number" ).each(

// For each number, run this code. The "intIndex" is the 
// loop iteration index on the current element.
function( intIndex ){

// Bind the onclick event to simply alert the iteration index value.
    $( this ).bind ("click", function(){
        alert( "Numbered index: " + intIndex );
    });
});

What are some examples of practical uses of the .each method you are using in your code? What exactly does $(this) represent?

2
  • each can be pretty important when you create plugins, anywhere you need to work on each element the selector specifies where the built in manipulators don't allow.. also 'this' refers to a pure html element, $(this) is the element wrapped in a jquery set, which allows it to call jquery methods. Commented Apr 6, 2009 at 19:39
  • @meandmycode: this refers to the pure html element or the pure DOM object from the selection? Commented Apr 6, 2009 at 20:20

8 Answers 8

56

Note there are two types of jQuery's each, the one iterates over and returns jQuery objects, the other is a more generic version.

Core/each
Example: Create a csv of all the hrefs on the page. (iterates over matching DOM elements and 'this' reffers to the current element)

 var hrefs = "";

 $("a").each(function() { 
     var href = $(this).attr('href');
     if (href != undefined && href != "") {
         hrefs = hrefs + (hrefs.length > 0 ? "," + href : href);
     }
 });

 alert(hrefs);

Utilities/jQuery.each
Iterating over an array or the elements of an object: (via: jQuery Documentation)

$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});

$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});
Sign up to request clarification or add additional context in comments.

3 Comments

@rizzle - I couldn't get your first example to work. Here is how I got it to work in Firebug for this page: var hrefs = ""; $( "a" ).each(function(){ var href = $(this).attr('href'); if (href != undefined) { hrefs += hrefs + href.length > 0 ? "," + href : href; } }); alert(hrefs);
heh, the error is that i was doing href.length instead of hrefs.length. I check the length to see if i should prepend the comma for the list. sorry i should have tested
heh you're right, i had to cater for undefined as well. I've updated the code.
9

I sometimes use it for traversing a large number of subelements in an XML data resultset

   my parsedData = [];  
   $('result', data).each(function() {
      parsedData.push(  
         { name: $('name', this).text(),
           addr: $('addr', this).text(),
           city: $('city', this).text(),
           state: $('state', this).text(),
           zip: $('zip', this).text()
      });

That works pretty nicely.

5 Comments

I've not seen this structure before - is the second argument a set of XML nodes?
Heh, yep - the second argument is the 'context', which defaults to current document, but can actually be any DOM or document. ( docs.jquery.com/Core/jQuery ) Handy. :)
This is cool. Like Peter I needed to figure out what was going on. What exactly is push? A array method to add to the array?
Yeah, push is a native JS func for arrays. For each of the "result" elements of the XML, it pushes into the array the object being created. By using "this" in the context argument of .each, some time is saved parsing the document. Handy if you have lots of flattening/filtering in an XML doc to do.
Another way to put it: push is pretty much the same as: myarray[myarray.length] = something; (but nicer). Array.shift also comes in handy at times.
6

A simple use, but it's very handy for iterating over a table and striping alternate rows:

// Adds CSS styling to alternate rows of tables marked with a .data class attribute.
$("table.data").each(function() {
    if (!$(this).hasClass("noStriping")) {
        $(this).find("tbody tr:nth-child(odd)").addClass("odd");
        $(this).find("tbody tr:nth-child(even)").addClass("even");
    }
});

6 Comments

i'd rather use $("tr:odd").addClass("odd");
This is better done with $('.classname:even').addClass('oddRow').
indeed! or $("tr:even").addClass('even');
Should be selecting with "tbody tr:odd" - since you generally only want the main data striped, not the head (or foot) sections. You are all structuring your tables with thead/tbody tags, right?
Caching $(this) is almost a no-brainer as well. The original has certainly proven to be a great jumping-off point for understandability and discussion, though!
|
6

I use the .each() method for ASP.NET WebMethod calls that return JSON strings. In this example, it populates a listbox with the values returned from the Ajax call:

async: true,
type: "POST",
url: "Example.aspx/GetValues",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
  var list = $('<select />');

  $.each(data.d, function(){
       var val = this.Value;
       var text = this.Text;
       list.append($('<option />').val(val).text(text));
  });

  $('#listbox').empty().append(list.find('option'));
},

ASP.NET has a built-in JSON serializer that automagically converts a class into the JSON string you see at the bottom of this post. Here is an example class that can be returned by the WebMethod:

public class Tuple
{
    public string Text;
    public int Value;

    public Tuple(string text, int val)
    {
        Text = text;
        Value = val;
    }
}

And the WebMethod itself:

[WebMethod]
public static List<Tuple> GetValues()
{
    List<Tuple> options = new List<Tuple>();
    options.Add(new Tuple("First option", 1));
    options.Add(new Tuple("Second option", 2));
    return options;
}

When you specify dataType: "json" in the jQuery Ajax options, the string is automatically converted into a Javascript object, so you can simply type this.Text or this.Value to get the data.

Here is the resulting JSON returned from the WebMethod above:

{"d":[{"Value":1,"Text":"First option"},{"Value":2,"Text":"Second option"}]}

Note: the data.d parameter (and likewise the first value seen in the JSON string) is explained here.

1 Comment

Yeah this is a cool practical example. I like it. Can you edit it with a sample JSON example? I assume Value and Text are variables in your JSON?
3

$.each() use as for loop, and $(this) refer the current object of the loop. Here in below example, where we loop over table row $(this) represents the current row it iterates.

Loop through an Array

// here's the array variable
 var myArray = ["apple", "mango", "orange", "grapes", "banana"];

 $.each(myArray, function (index, value) {
      console.log(index+' : '+value);
 });

Loop through Table Row (HTML element)

 $("#myTable tr").each(function () {
        var self = $(this);
        var col_1_value = self.find("td:eq(0)").text().trim();
        var col_2_value = self.find("td:eq(1)").text().trim();
        var col_3_value = self.find("td:eq(2)").text().trim();
        var col_4_value = self.find("td:eq(3)").text().trim();
        var result = col_1_value + " - " + col_2_value + " - " + col_3_value + " - " + col_4_value;
        console.log(result);
 });

My article Understanding jQuery .each()

Comments

2

each() is an iterator function used to loop over object, arrays, and array-like objects. Plain objects are iterated via their named properties while arrays and array-like objects are iterated via their indices.

For example:

Array Iteration using .each() method

$.each( arr, function( index, value ){
  //code here
});

Plain Object Iteration using .each method

$.each( { firstName: "Amit", lastName: "Gupta" }, function(firstName, lastName){
    console.log( " First Name: " + firstName + " Last Name: " + lastName);
});

Comments

1

You use the each function to access/modify any dom property that isn't wrapped by jquery.

I often have a grid/table with a column containing checkboxes.

I write a selector to get the list of checkboxes, then set the checked property to true/false. (for check all, uncheck all).

You have to use the each function for that.

$(".mycheckbox").each(function() { this.checked = true; });

2 Comments

Can't you do $(".mycheckbox").attr('checked',true); ?
@Peter, along those lines, i've had better luck with $(".mycheckbox").attr('checked','checked');
1

Here are tutorial links:

$(function(){
            var ArrList=["Jaipur","Udaipur","Kota","Ahmedabad","Surat"];
                $(ArrList).each(function(index,item){
                    $("ul").append("<li>"+item+"</li>");
                });
        });

https://www.youtube.com/watch?v=qiYdTv_sZyU

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.