$.each() in jquery
The $.each()
function in jQuery is a versatile utility that allows you to iterate over arrays and objects. It executes a function for each element in the collection, making it useful for tasks like manipulating or accessing data within arrays or objects.
Syntax
For Arrays:
$.each(array, function(index, value) {
// Code to execute for each element
});
For Objects:
$.each(object, function(key, value) {
// Code to execute for each property
});
Parameters
- array/object: The array or object to iterate over.
- function(index/key, value): A callback function that is executed for each element or property.
- index/key: The index (for arrays) or key (for objects) of the current element or property.
- value: The value of the current element or property.
Return Value
$.each()
always returns the original collection, which allows for chaining.
Examples
Iterating Over an Array
var fruits = ['apple', 'banana', 'cherry'];
$.each(fruits, function(index, value) {
console.log(index + ': ' + value);
});
Output:
0: apple
1: banana
2: cherry
Iterating Over an Object
var person = {
name: 'John',
age: 30,
city: 'New York'
};
$.each(person, function(key, value) {
console.log(key + ': ' + value);
});
Output:
name: John
age: 30
city: New York
Key Points
- Order of Iteration: For arrays,
$.each()
iterates from index 0 to the end. For objects, it iterates over the properties in an arbitrary order. - Modification: You can modify the elements or properties directly within the callback function.
- Early Exit: To stop iteration early, you can return
false
from the callback function.
$.each(fruits, function(index, value) {
if (value === 'banana') {
return false; // Stops the iteration
}
console.log(index + ': ' + value);
});
Output:
0: apple
1: banana
The $.each()
function is a powerful tool in jQuery for handling collections of data and is particularly useful for working with dynamic content.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.