jQuery Chaining and $.each()
Method Chaining
jQuery methods return the jQuery object, so you can chain multiple calls.
$("p")
.addClass("highlight")
.css("color", "blue")
.slideDown(300)
.animate({opacity: 0.8}, 500);
$("#myDiv")
.find("h3")
.addClass("title")
.end() // back to #myDiv
.find("p")
.addClass("text");$.each() — Iterate Elements
$("li").each(function(index, element) {
console.log(index, $(element).text());
});
// Shorthand
$("li").each(function() {
$(this).css("color", "red");
});$.each() — Iterate Arrays/Objects
var fruits = ["apple", "banana", "cherry"];
$.each(fruits, function(i, val) {
console.log(i + ": " + val);
});
$.each({name: "Alice", age: 30}, function(key, val) {
console.log(key + " = " + val);
});