Skip to content

Instantly share code, notes, and snippets.

@trentmiller
Created March 22, 2013 16:04
Show Gist options
  • Save trentmiller/5222480 to your computer and use it in GitHub Desktop.
Save trentmiller/5222480 to your computer and use it in GitHub Desktop.
Popular jQuery using .each()
$('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
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));
});
//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 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
<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
jQuery('#5demo').bind('click', function(e)
{
    jQuery('li').each(function(i)
    {
        jQuery(this).css("background-color","orange");
        jQuery(this).delay(i*200).fadeOut(1500);
    });
});
(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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment