Traversing Each
## jQuery each() Method
The `each()` method is a core traversal utility in jQuery. It specifies a function to run for each matched element in a jQuery selection. It provides a clean, declarative way to iterate over DOM elements, arrays, or objects.
---
### Definition and Usage
The `each()` method executes a callback function for every element in the matched set.
* **Context (`this`):** Within the callback function, the `this` keyword refers to the current DOM element. To use jQuery methods on the current element, you must wrap it in the jQuery selector: `$(this)`.
* **Early Termination:** You can stop the loop early (similar to using a `break` statement in a standard loop) by returning `false` from the callback function. Returning non-false (or `true`) acts like a `continue` statement, skipping to the next iteration.
---
### Syntax
```javascript
$(selector).each(function(index, element))
```
#### Parameter Values
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `function(index, element)` | **Required** | Specifies the function to run for each matched element. |
| `index` | *Integer* | The index position of the current element within the matched set (zero-based). |
| `element` | *DOM Element* | The current DOM element (equivalent to the `this` keyword). |
---
### Code Examples
#### Example 1: Basic Iteration
The following example alerts the text content of each `` element when a button is clicked:
```javascript
$("button").click(function(){
$("li").each(function(){
// $(this) wraps the current DOM element in a jQuery object
alert($(this).text());
});
});
```
#### Example 2: Using Index and Element Parameters
You can pass the `index` and `element` parameters to the callback function to access the position and the raw DOM element directly:
```javascript
$("button").click(function(){
$("li").each(function(index, element){
// 'index' is the 0-based position
// 'element' is the raw DOM element (same as 'this')
console.log("Element " + index + " text: " + $(element).text());
});
});
```
#### Example 3: Breaking Out of the Loop Early
To stop the loop before iterating through all elements, return `false`:
```javascript
$("li").each(function(index) {
if ($(this).text() === "Stop") {
return false; // This breaks out of the each() loop completely
}
$(this).addClass("highlight");
});
```
---
### Considerations & Best Practices
1. **Performance:** While `each()` is highly readable, native JavaScript loops (like `for...of` or `Array.prototype.forEach()`) are generally faster. For performance-critical code involving thousands of elements, consider using native APIs.
2. **Implicit Iteration:** Many jQuery methods (such as `.css()`, `.addClass()`, or `.attr()`) automatically apply to all elements in the selection. You do not need to wrap them in an `each()` loop unless you need to perform custom logic or calculations per element.
* *Unnecessary:* `$('p').each(function() { $(this).addClass('active'); });`
* *Preferred:* `$('p').addClass('active');`
3. **`$.each()` vs `$().each()`:**
* `$().each()` (documented here) is used exclusively for iterating over a jQuery collection of DOM elements.
* `$.each()` is a generic utility function used to iterate over arbitrary JavaScript arrays or objects.
YouTip