How to use each() in jQuery?

The .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 allows you to perform custom actions or operations on each element within the selected set.

Syntax:
$(selector).each(function(index, element) { // Your code here });
  1. selector: The jQuery selector that targets the elements you want to iterate over.
  2. index: An optional parameter representing the index of the current element in the set.
  3. element: An optional parameter representing the current DOM element in the set.

Iterating Over a List of Items

Suppose you have an unordered list ( <ul> ) with several list items ( <li> ) that you want to manipulate individually:

<ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> $("#myList li").each(function(index, element) { // `index` represents the index of the current <li> element (0, 1, 2, ...) // `element` is the current <li> DOM element var text = $(this).text(); // Get the text content of the <li> console.log("Item " + (index + 1) + ": " + text); // Output the item text });

In this example, we select all the list items inside the <ul> with the ID "myList" using $("#myList li"). Then, we use .each() to iterate over each list item. Inside the callback function, we access the text content of each list item using $(this).text() and output it to the console along with the item's index.

Common Use Cases:

  1. Manipulating or modifying individual elements within a collection.
  2. Applying custom logic or functionality to each element in a set.
  3. Performing operations like validation or formatting on a group of elements.

Conclusion

The .each() function 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.