How do you use jQuery's each() method to iterate over a collection of DOM elements?
How do you use jQuery's each() method to iterate over a collection of DOM elements?
487
09-May-2023
Updated on 11-May-2023
Aryan Kumar
11-May-2023In jQuery, the each() method is used to iterate over a collection of DOM elements and perform an action on each element. Here's an example of how to use the each() method:
In this example, we use the jQuery selector $('ul li') to select all li elements that are children of a ul element. We then call the each() method on the resulting collection of elements.
The each() method takes a callback function as its argument, which is called for each element in the collection. The callback function takes two arguments: the index of the current element in the collection, and a reference to the current element itself.
In the example above, we pass a callback function that logs the index of each li element in the console, along with its text content. The $(this) keyword is used to reference the current li element in the callback function.
Here are a few more things to keep in mind when using the each() method in jQuery:
By using the each() method in jQuery, you can easily iterate over a collection of DOM elements and perform actions on each element as needed.