How to use for each in jQuery
By FoxLearn Published on Sep 16, 2024 303
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.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
Nov 17, 2024
RuangAdmin Template
Nov 13, 2024
Admin BSB Free Bootstrap Admin Dashboard
Nov 14, 2024