In jQuery, you can iterate over sets of elements using the .each()
method. This method allows you to perform a function on each element in the set individually. Here's how it works:
Basic Iteration:
.each()
method to iterate over a set of elements.javascript$('li').each(function(index, element) {
// Code to execute for each <li> element
console.log(index, $(element).text());
});
This code iterates over each <li>
element on the page and logs its index and text content to the console.
Using this
and $(this)
:
.each()
callback function, this
refers to the current DOM element, while $(this)
wraps it in a jQuery object.javascript$('li').each(function() {
// Code to execute for each <li> element
console.log($(this).text());
});
This code achieves the same result as the previous example but uses $(this)
to access the text content of each <li>
element directly.
Accessing Index:
javascript$('li').each(function(index) {
// Code to execute for each <li> element
console.log(index, $(this).text());
});
This code logs the index of each <li>
element along with its text content.
Exiting Early:
false
from the .each()
callback function to exit the loop early.javascript$('li').each(function(index, element) {
if (index === 3) {
return false; // Exit loop when index is 3
}
console.log(index, $(element).text());
});
This code stops iterating over <li>
elements when the index reaches 3.
Using Arrow Function:
.each()
.javascript$('li').each((index, element) => {
console.log(index, $(element).text());
});
This is a concise way to achieve the same result as before, using an arrow function syntax.
Iterating over elements in jQuery using .each()
allows you to perform actions on each element individually, making it a powerful tool for DOM manipulation and interaction.
Thanks for learning