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: The jQuery selector that targets the elements you want to iterate over.
- index: An optional parameter representing the index of the current element in the set.
- 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:
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:
- Manipulating or modifying individual elements within a collection.
- Applying custom logic or functionality to each element in a set.
- Performing operations like validation or formatting on a group of elements.
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.