In 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:
You can break out of the each() loop at any time by returning
false from the callback function.
You can access the length of the collection of elements using the length property. For example:
$('ul li').length.
You can use the this keyword in the callback function to access the current element without having to wrap it in a jQuery object. For example:
$(this).text() is equivalent to this.textContent.
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In 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.