The each()
function in jQuery is a versatile method that allows you to iterate over jQuery objects (collections of DOM elements) or arrays/objects.
1. Basic Usage: Iterating Over Elements
This example shows how to loop through all list items (<li>) and log their text content along with their index position.
1 2 3 4 |
// Loop through all <li> elements and log their text $('li').each(function(index) { console.log(index + ": " + $(this).text()); }); |
2. Modifying Multiple Elements
Here we add a CSS class to every other table row to create a striped table effect. This demonstrates how to modify elements during iteration.
1 2 3 4 5 6 |
// Add a class to every other table row $('tr').each(function(index) { if (index % 2 === 0) { $(this).addClass('even-row'); } }); |
3. Accessing Both Index and Element
This example shows how to access both the index and the element itself, adding data attributes to track each image’s position.
1 2 3 4 |
// Add data attributes with their positions to all images $('img').each(function(index, element) { $(element).attr('data-position', index); }); |
4. Breaking the Loop Early
Demonstrates how to exit the loop early by returning false. This is useful when searching for a specific element.
1 2 3 4 5 6 7 |
// Find the first input that's empty and focus it $('input').each(function() { if ($(this).val() === '') { $(this).focus(); return false; // breaks the loop } }); |
5. Iterating Over Arrays
Shows how to use $.each() to iterate through a regular JavaScript array, accessing both index and value.
1 2 3 4 5 |
// Process an array of values const colors = ['red', 'green', 'blue']; $.each(colors, function(index, value) { console.log(index + ": " + value); }); |
6. Iterating Over Objects
Demonstrates iterating through an object’s properties, accessing both keys and values in each iteration.
1 2 3 4 5 |
// Loop through an object's properties const person = {name: 'John', age: 30, occupation: 'Developer'}; $.each(person, function(key, value) { console.log(key + ": " + value); }); |
7. Dynamic Styling Based on Content
Shows how to examine element content during iteration and apply styling conditionally based on that content.
1 2 3 4 5 6 7 |
// Highlight prices over $100 $('.price').each(function() { const price = parseFloat($(this).text().replace('$', '')); if (price > 100) { $(this).addClass('expensive'); } }); |
8. Creating a Dynamic Menu
Demonstrates a practical use case where we generate a navigation menu by iterating through heading elements on the page.
1 2 3 4 5 6 7 8 9 |
// Generate a menu from h2 elements const $menu = $('#page-menu'); $('h2').each(function(index) { const title = $(this).text(); const menuItem = $('<a>').attr('href', '#section-' + index) .text(title); $menu.append($('<li>').append(menuItem)); $(this).attr('id', 'section-' + index); }); |
9. Form Field Validation
Shows how to use each() for form validation, checking multiple required fields in a single loop.
1 2 3 4 5 6 7 8 9 10 11 |
// Check if all required fields are filled let isValid = true; $('input[required]').each(function() { if ($(this).val().trim() === '') { isValid = false; $(this).addClass('error'); } }); if (!isValid) { alert('Please fill all required fields'); } |
10. Data Processing from Table Rows
Demonstrates extracting structured data from an HTML table by iterating through rows and collecting information into objects.
1 2 3 4 5 6 7 8 9 10 11 |
// Extract data from a table into an array of objects const products = []; $('table.products tr').each(function() { const $row = $(this); products.push({ id: $row.find('.id').text(), name: $row.find('.name').text(), price: $row.find('.price').text() }); }); console.log(products); |
Key Points to Remember:
$(selector).each()
iterates over jQuery objects (DOM elements)$.each(collection, callback)
iterates over arrays and objects- The callback receives
index
andelement
(orkey
andvalue
for objects) - Use
return false
to break out of the loop early $(this)
refers to the current element within the callback