This article discusses the jQuery.each() function in depth - one of the most important and commonly used functions in jQuery. We will explore its importance and learn how to use it.
Core points
What is jQuery.each()?
jQuery's each() function is used to loop through each element of the target jQuery object - an object containing one or more DOM elements, and expose all jQuery functions. It is very useful for multi-element DOM operations and iterating over arbitrary array and object properties.
In addition to this function, jQuery also provides a helper function with the same name that can be called without prior selection or creation of any DOM elements.
jQuery.each() Syntax
Let's take a look at the practical application of different modes.
The following example selects each <div> element on the web page and outputs the index and ID of each element:
<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// DOM 元素
$('div').each(function(index, value) {
console.log(`div${index}: ${this.id}`);
});</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>
<p>The possible output results are: </p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><code>div0:header
div1:main
div2:footer</code></pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>
<p>This version uses jQuery's <code>$(selector).each()
function, not practical functions.
The next example shows the use of practical functions. In this case, the object to be looped over is given as the first parameter. In this example, we will show how to loop through the array:
// 数组 const arr = [ 'one', 'two', 'three', 'four', 'five' ]; $.each(arr, function(index, value) { console.log(value); // 将在 "three" 后停止运行 return (value !== 'three'); }); // 输出:one two three
In the last example, we want to demonstrate how to iterate over the properties of an object:
// 对象 const obj = { one: 1, two: 2, three: 3, four: 4, five: 5 }; $.each(obj, function(key, value) { console.log(value); }); // 输出:1 2 3 4 5
All this boils down to providing the appropriate callback function. The context of the callback function this
will be equal to its second parameter, the current value. However, since the context is always an object, the original value must be wrapped:
$.each({ one: 1, two: 2 } , function(key, value) { console.log(this); }); // Number { 1 } // Number { 2 }
This means there is no strict equality between the value and the context.
$.each({ one: 1 } , function(key, value) { console.log(this == value); console.log(this === value); }); // true // false
The first parameter is the current index, which is a number (for arrays) or a string (for objects).
Let's see how the jQuery.each() function is used in conjunction with jQuery objects. The first example selects all a
elements in the page and outputs their href
properties:
$('a').each(function(index, value){ console.log(this.href); });
The second example outputs each external href
on the webpage (assuming only the HTTP(S) protocol):
$('a').each(function(index, value){ const link = this.href; if (link.match(/https?:\/\//)) { console.log(link); } });
Suppose there is the following link on the page:
<a href="https://www.php.cn/link/9a4b930f7a36153ca68fdf211c8836a7">SitePoint</a> <a href="https://www.php.cn/link/235fba44e32ba4dd3a3f72db1a8a6846">MDN web docs</a> <a href="https://www.php.cn/link/60c4a88bac6125d490af523a8c94e5e1">Example Domain</a>
The second example will output:
// DOM 元素 $('div').each(function(index, value) { console.log(`div${index}: ${this.id}`); });
We should note that the DOM element from the jQuery object is "native" form in the callback function it passes to jQuery.each(). The reason is that jQuery is actually just a wrapper for arrays of DOM elements. By using jQuery.each(), this array is iterated in the same way as a normal array. Therefore, we won't get the elements of the packaging out of the box.
About our second example, this means we can get the this.href
attribute of the element by writing href
. If we want to use jQuery's attr()
method, we need to repackage the element like this: $(this).attr('href')
.
Let's see how to deal with normal arrays:
<code>div0:header div1:main div2:footer</code>
This code snippet output:
// 数组 const arr = [ 'one', 'two', 'three', 'four', 'five' ]; $.each(arr, function(index, value) { console.log(value); // 将在 "three" 后停止运行 return (value !== 'three'); }); // 输出:one two three
Nothing special here. The array has a numeric index, so we get numbers starting from 0 to N-1 where N is the number of elements in the array.
We may have more complex data structures, such as arrays in arrays, objects in objects, objects in arrays, or arrays in objects. Let's see how jQuery.each() can help us in this case:
// 对象 const obj = { one: 1, two: 2, three: 3, four: 4, five: 5 }; $.each(obj, function(key, value) { console.log(value); }); // 输出:1 2 3 4 5
This example output:
$.each({ one: 1, two: 2 } , function(key, value) { console.log(this); }); // Number { 1 } // Number { 2 }
We use nested calls to jQuery.each() to handle nested structures. The external call handles the array of variable colors; the internal call handles each object. In this example, there is only one key per object, but you can usually use this code to process any number of keys.
This example demonstrates how to loop through each element of the class productDescription assigned (given in the HTML below):
$.each({ one: 1 } , function(key, value) { console.log(this == value); console.log(this === value); }); // true // false
We use each() helper function instead of each() method on the selector.
$('a').each(function(index, value){ console.log(this.href); });
In this case, the output is:
$('a').each(function(index, value){ const link = this.href; if (link.match(/https?:\/\//)) { console.log(link); } });
We don't have to include index and value. These are just parameters that help determine which DOM element we are currently iterating over. In addition, in this case, we can also use a more convenient each method. We can write this way:
<a href="https://www.php.cn/link/9a4b930f7a36153ca68fdf211c8836a7">SitePoint</a> <a href="https://www.php.cn/link/235fba44e32ba4dd3a3f72db1a8a6846">MDN web docs</a> <a href="https://www.php.cn/link/60c4a88bac6125d490af523a8c94e5e1">Example Domain</a>
We will get in the console:
<code>https://www.php.cn/link/9a4b930f7a36153ca68fdf211c8836a7 https://www.php.cn/link/235fba44e32ba4dd3a3f72db1a8a6846 https://www.php.cn/link/60c4a88bac6125d490af523a8c94e5e1</code>
Note that we are wrapping the DOM element in a new jQuery instance so that we can use jQuery's text() method to get the text content of the element.
In the next example, when the user clicks an element with ID 5demo, all list items will be set to orange immediately.
const numbers = [1, 2, 3, 4, 5]; $.each(numbers, function(index, value){ console.log(`${index}: ${value}`); });
After the index-related delay (0, 200, 400...ms), we fade the element out:
<code>0:1 1:2 2:3 3:4 4:5</code>
Conclusion
In this article, we demonstrate how to iterate over DOM elements, arrays, and objects using the jQuery.each() function. This is a powerful and time-saving function that developers should incorporate into their own toolkit.
If jQuery is not your preferred choice, you may want to consider using JavaScript native Object.keys()
and Array.prototype.forEach()
methods. There are also libraries like foreach that allow you to iterate over key-value pairs of class array objects or dictionary objects.
Remember: $.each()
and $(selector).each()
are two different methods defined in two different ways.
(This article was updated in 2020 to reflect current best practices and update the conclusions about native solutions using modern JavaScript. To learn more about JavaScript, read our book JavaScript : From Novice to Ninja, Second Edition》)
Frequently Asked Questions about jQuery each() function
What is the purpose of the .each() function in jQuery? The .each() function in jQuery is used to iterate over a collection of DOM elements and perform specific operations on each element.
How to use the .each() function in jQuery? You can use the .each() function by selecting a set of elements using the jQuery selector and then calling .each() on that selection. You provide a callback function that defines the action to be performed on each element.
What are the parameters of the callback function used with .each()? The callback function accepts two parameters: index (the current index of the element in the collection) and element (the current DOM element being iterated).
How to use index parameter in .each() callback function? You can use the index parameter to track the position of the current element in the collection, which is very useful for conditional operations or other operations.
What are some common use cases for the.each() function? Common use cases include iterating over a list of elements to manipulate their properties, values, or styles, and performing custom actions on each element in the collection.
The above is the detailed content of 5 jQuery.each() Function Examples. For more information, please follow other related articles on the PHP Chinese website!