How to use for each in jQuery

By FoxLearn 9/16/2024 2:42:18 AM   59
In jQuery, the .each() method is used to iterate over a jQuery object, executing a function for each matched element.

How to use for each in JQuery

Here’s the basic syntax:

$(selector).each(function(index, element) {
    // execute for each element
});

Parameter

  • index: The index of the current element in the jQuery collection.
  • element: The actual DOM element at that index.

For example if you have a list of items and you want to add a class to each item.

<ul id="list">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

Javascript:

$('#list li').each(function(index, element) {
    $(this).addClass('highlight');
});

In this example, $(this) refers to the current li element in the iteration. The .addClass('highlight') method is called on each li element.

You can also use the index and element parameters if you need to perform different actions based on the index or if you need direct access to the DOM element as shown below.

$('#list li').each(function(index, element) {
    $(element).text('Updated Item ' + (index + 1));
});

The .each() method in jQuery provides an easy way to perform actions on each item in the collection without needing to manually handle DOM manipulation or index tracking.