use of each function in jQuery

each() function in jQuery is used to iterate over a set of elements, typically obtained using a selector, and apply a specified function to each element individually. It is a powerful tool for working with collections of elements in jQuery, making it easy to iterate through and apply actions to each element individually.

each  function in jQuery


The syntax for each() function is as follows:
$(selector).each(function(index, element) {
  // code to be executed for each element
});
The selector parameter specifies the set of elements to iterate over. The function parameter is a callback function that is executed for each element in the set. The index parameter specifies the index of the current element in the set, and the element parameter specifies the current element itself.
The following is an example of how to use the each() function to iterate over a set of elements and change their background color:
$("p").each(function(index, element) {
  $(element).css("background-color", "red");
});
This code will iterate over all of the paragraph elements on the page and change their background color to red.
The each() function can also be used to iterate over arrays and objects. In the case of an array, the callback function is passed the array index and a corresponding array value each time. In the case of an object, the callback function is passed the object property name and a corresponding object value each time.
The each() function is a powerful and versatile tool that can be used to perform a variety of tasks on collections of elements in jQuery.

Post a Comment

2 Comments