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
-
The
- jQuery.each() function is a multi-function tool in jQuery that iterates over DOM elements, arrays, and objects, so as to efficiently perform multi-element DOM operations and data processing.
- This function provides two modes of operation: as a method called on a jQuery object (for DOM elements), and as a practical function for arrays and objects, each mode is suitable for different types of data structures.
- With practical examples, this article demonstrates the power and flexibility of jQuery.each(), highlights its importance in simplifying iterations, and highlights alternative JavaScript methods for performing similar tasks.
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:
<pre class='brush:php;toolbar:false;'>// DOM 元素
$('div').each(function(index, value) {
console.log(`div${index}: ${this.id}`);
});</pre>
<p>The possible output results are: </p>
<pre class="brush:php;toolbar:false"><code>div0:header
div1:main
div2:footer</code></pre>
<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:
// 數(shù)組 const arr = [ 'one', 'two', 'three', 'four', 'five' ]; $.each(arr, function(index, value) { console.log(value); // 將在 "three" 后停止運(yùn)行 return (value !== 'three'); }); // 輸出:one two three
In the last example, we want to demonstrate how to iterate over the properties of an object:
// 對(duì)象 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).
- Basic jQuery.each() function example
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="http://www.miracleart.cn/link/9a4b930f7a36153ca68fdf211c8836a7">SitePoint</a> <a href="http://www.miracleart.cn/link/235fba44e32ba4dd3a3f72db1a8a6846">MDN web docs</a> <a href="http://www.miracleart.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')
.
- jQuery.each() array example
Let's see how to deal with normal arrays:
<code>div0:header div1:main div2:footer</code>
This code snippet output:
// 數(shù)組 const arr = [ 'one', 'two', 'three', 'four', 'five' ]; $.each(arr, function(index, value) { console.log(value); // 將在 "three" 后停止運(yùn)行 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.
- jQuery.each() JSON example
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:
// 對(duì)象 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.
- jQuery.each() class example
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="http://www.miracleart.cn/link/9a4b930f7a36153ca68fdf211c8836a7">SitePoint</a> <a href="http://www.miracleart.cn/link/235fba44e32ba4dd3a3f72db1a8a6846">MDN web docs</a> <a href="http://www.miracleart.cn/link/60c4a88bac6125d490af523a8c94e5e1">Example Domain</a>
We will get in the console:
<code>http://www.miracleart.cn/link/9a4b930f7a36153ca68fdf211c8836a7 http://www.miracleart.cn/link/235fba44e32ba4dd3a3f72db1a8a6846 http://www.miracleart.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.
- jQuery.each() Delay Example
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.
