5 jQuery.each() Function Examples

Sam Deering

OK, this is quite an extensive overview of the jQuery .each() function. This is one of jQuery’s most important and most used functions so that’s the reason why I’ve chosen to go into such detail about it and really get down and dirty about how to use it to it’s full useful potential!

Related posts:

Firstly, what is jQuery .each()

Basically, the jQuery .each() function is used to loop through each element of the target jQuery object. Very useful for multi element DOM manipulation, looping arrays and object properties.

jQuery .each() Syntax

//DOM ELEMENTS
$("div").each(function(index, value) { 
    console.log('div' + index + ':' + $(this).attr('id')); 
});
//outputs the ids of every div on the web page
//ie - div1:header, div2:body, div3:footer

//ARRAYS
var arr = [ "one", "two", "three", "four", "five" ];
jQuery.each(arr, function(index, value) {
       console.log(this);
       return (this != "three"); // will stop running after "three"
   });
//outputs: one two three

//OBJECTS
var obj = { one:1, two:2, three:3, four:4, five:5 };
    jQuery.each(obj, function(i, val) {
       console.log(val);
    });
//outputs: 1 2 3 4 5

For a more advanced jQuery.each example see Create Text Excerpts for Paragraphs on your web page.

1. Basic jQuery.each() Function Example

$('a').each(function(index, value){
      console.log($(this).attr('href'));
});
//outputs: every links href element on your web page

$('a').each(function(index, value){
	var ihref = $(this).attr('href');
	if (ihref.indexOf("http") >= 0) 
	{
		console.log(ihref+'<br />');
	}
});
//outputs: every external href on your web page

eg – if you had the following links anywhere on your web page:

<a href="http://www.jquery4u.com">JQUERY4U</a>
<a href="http://www.phpscripts4u.com">PHP4U</a>
<a href="http://www.blogoola.com">BLOGOOLA</a>

It would output:


http://jquery4u.com


http://www.phpscripts4u.com


http://www.blogoola.com

2. jQuery.each() Array Example

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value); 
});
//outputs: 1:1 2:2 3:3 4:4 5:5

3. jQuery.each() JSON Example

(function($) {
var json = [ 
    { "red": "#f00" },
    { "green": "#0f0" },
    { "blue": "#00f" }
];

$.each(json, function() {
  $.each(this, function(name, value) {
    /// do stuff
    console.log(name + '=' + value);
  });
});
//outputs: red=#f00 green=#0f0 blue=#00f
})(jQuery);

Also see 10 Example JSON Files.

4. jQuery.each() Class Example

This example shows you how to loop through each element with class=”productDescription” given in the HTML below.

Update: 19/03/13 – This jsfiddle shows you the object types returned by $.each() if your confused about [object HTMLDivElement] it should help clear it up.

<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
$.each($('.productDescription'), function(index, value) { 
    console.log(index + ':' + value); 
});
//outputs: 1:Red 2:Orange 3:Green

You don’t have to include index and value these are just parameters which help determine which DOM element your currently iterating. You could also write it like this:

$.each($('.productDescription'), function() { 
    console.log($(this).html());
});
//outputs: Red Orange Green

5. jQuery.each() Delay Example

Click to see it in action
This is awesome! Look up at the menu at the top as this contains the first list items on the page!.

jQuery('#5demo').bind('click', function(e)
{
    jQuery('li').each(function(i)
    {
        jQuery(this).css("background-color","orange");
        jQuery(this).delay(i*200).fadeOut(1500);
    });
});

Conclusion

Make use of the .each function as much as you can because it’s fast and will save you heaps of time!

Remember: $.each() and $(selector).each() are two different methods defined in two different ways, one with jQuery.each = function and the other with jquery.fn.each = function.

Note: the console.log() commands are just for use with firebug.

jQuery Each Function Examples

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Pingback: jsblog » .each

  • Pingback: jQuery Get All Occurrences of a String inside a String | jQuery4u

  • http://www.bladeronline.com umesh

    thank you for your great example..

    • http://jquery4u.com/ jQuery4u

      Test image post for Disqus.

  • http://dixanta.com.np dixanta shrestha

    thanks a lot you have saved my life.. thanks for sharing such a wonderful tips. cheers

  • http://www.rvbattery.tk peak

    great for jquery tips and bookmark this web

  • Maruf

    Thanks … great tutorial.

  • vani

    thank you……. .Its very helpfull

  • http://jquery4u.com/ jQuery4u

    @92ffa64c666366e53a419d777bb07d67:disqus @ebd31b9087aefbb26fc6233839d5705e:disqus @14a18fec758327f256b570620cea4578:disqus @a73ce5e4d966b8e3ab87b4fa8d3ccab1:disqus @4c8fe5b1f86db3af3083989987a74abd:disqus  – Thanks guys, much appreciated.

  • Greg

    these type of posts are the best! thanks! lots of example how to use $.each – just used the json example :)

    • http://jquery4u.com/ jQuery4u

      Thanks Greg!

  • http://alphacorner.eu/ poradnik fotograficzny

     Example for point 5 doesn’t work. (FF13 – opens new window)

    • http://jquery4u.com/ jQuery4u

      Hi Poradnik.

      Thanks mate, I’ve fixed it up! 

      Sam

  • Pingback: Useful jQuery Function Demos For Your Projects | Layout to HTML

  • Pingback: Use jQuery to Create Excerpts for Text Elements | jQuery4u

  • http://twitter.com/websnippetz Karthik

    Very nice examples, got 100% idea how to use each(), thanks for the nice tut:)

    • http://jquery4u.com/ jQuery4u

      Thanks! :)

  • Ameenullah

    Thanks aton!! saved my time :)

  • http://twitter.com/stuy1974 Stu Gardner-Vaughan

    Should the outputs for example 2 be:

    //outputs: 1:0 2:1 3:2 4:3 5:4 6:5

    instead of

    //outputs: 1:1 2:2 3:3 4:4 5:5

    ?

    • http://www.facebook.com/dinatih David Dinatih

      No, it should be 0:0 1:1 2:2 3:3 4:4 5:5

      • http://jquery4u.com/ jQuery4u

        David is right, just paste into your console Stu to check it out.

        • doctor_house_md

          Why not correct the example?

  • Pingback: Useful jQuery Function Demos For Your Projects

  • DarylKing

    For me Part A of example 4 outputs this. Any idea why that would be?

    0:[object HTMLDivElement]
    1:[object HTMLDivElement]
    2:[object HTMLDivElement]

    • http://jquery4u.com/ jQuery4u

      Hi Daryl, I’ve done this quick jsfiddle example for you hopefully it will help you understand. http://jsfiddle.net/ryDed/

      • DarylKing

        Thanks for that Sam (and for pointing out jsfiddle – its a great resource). Its just that the “//outputs: 1:Red 2:Orange 3:Green” under the example puzzled me. Cheers.

        • Raja

          What is the difference between this I was confused?
          1) $.each($(‘.colors’), function(index, value) {

          console.log(index + ‘:’ + value);
          });// Whether i can get the value as $(value) in this 1st example. If not y?

          2) $(‘.colors’).each(function(index, value) {

          console.log($(value));

          });

  • atomxml.org

    Thanks. :)

  • Pingback: 50 jQuery Function Demos for Aspiring Web Developers - Smashing Coding

  • Allan McAvoy

    Very helpful, Thanks Sam!

  • Manish’s Astral Manifestation

    what an awesome post… useful right away. Just used the $.each function to iterate over a nested JSON object. Thanks a lot for this.

    This is why i love this site so much…

    • http://jquery4u.com/ jQuery4u

      Thanks bro! :)

  • Pingback: Useful jQuery Function Demos For Your Projects - Internet Business

  • Vasu Chowdari

    $(‘a’).each(function (index, value) {
    console.log($(this).attr(‘href’));
    alert(‘hai’);
    });
    alert messge was not displayed

  • Pingback: Useful link for Developer | Vairam Blog