.each( function )Returns: jQuery
Description: Iterate over a jQuery object, executing a function for each matched element.
-
version added: 1.0.each( function )
-
functionA function to execute for each matched element.
-
The .each()
method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this
refers to the element.
Suppose you have a simple unordered list on the page:
1
2
3
4
|
|
You can select the list items and iterate across them:
1
2
3
|
|
A message is thus logged for each item in the list:
0: foo
1: bar
You can stop the loop from within the callback function by returning false
.
Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known as implicit iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each()
method:
1
2
3
4
5
6
7
|
|
Examples:
Iterate over three divs and sets their color property.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
|
Demo:
To access a jQuery object instead of the regular DOM element, use $( this )
. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
|
Demo:
Use return false
to break out of each() loops early.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
|