trentmiller
3/22/2013 - 4:04 PM

Popular jQuery using .each()

Popular jQuery using .each()

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

-------------------------
$.each($('.productDescription'), function() { 
    console.log($(this).html());
});
//outputs: Red Orange Green
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
//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
    var arr = [ "one", "two", "three", "four", "five" ];
    var obj = { one:1, two:2, three:3, four:4, five:5 };

    jQuery.each(arr, function() {
      $("#" + this).text("My id is " + this + ".");
      return (this != "four"); // will stop running to skip "five"
    });

    jQuery.each(obj, function(i, val) {
      $("#" + i).append(document.createTextNode(" - " + val));
    });
$('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