---
title: "How do you use jQuery's each() method to iterate over a collection of DOM elements?"  
description: "How do you use jQuery's each() method to iterate over a collection of DOM elements?"  
author: "Revati S Misra"  
published: 2023-05-09  
updated: 2023-05-11  
canonical: https://www.mindstick.com/forum/158255/how-do-you-use-jquery-s-each-method-to-iterate-over-a-collection-of-dom-elements  
category: "jquery"  
tags: ["jquery", "jquery selectors", "jquery validate"]  
reading_time: 2 minutes  

---

# How do you use jQuery's each() method to iterate over a collection of DOM elements?

How do you use jQuery's each() [method](https://www.mindstick.com/forum/166/webservice-method) to iterate over a [collection](https://www.mindstick.com/articles/1718/collections-in-java) of [DOM](https://www.mindstick.com/blog/304003/what-is-the-difference-between-virtual-dom-and-shadow-dom) [elements](https://www.mindstick.com/forum/1440/wpf-button-with-multiple-text-elements)?

## Replies

### Reply by Aryan Kumar

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:

```javascript
$('ul li').each(function(index) {
 console.log(index + ': ' + $(this).text());
});
```

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.


---

Original Source: https://www.mindstick.com/forum/158255/how-do-you-use-jquery-s-each-method-to-iterate-over-a-collection-of-dom-elements

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
