EN
jQuery - each method usage examples
14 points
In this quick article, we are going to discuss how to use jQuery each method. There are two cases where we can use $.each
method: arrays and objects.
Quick overview:
each
method with arrays
xxxxxxxxxx
1
var array = ['item 1', 'item 2', 'item 3'];
2
3
$.each(array, function(index, item) {
4
console.log(index + ': ' + item);
5
});
each
method with objects
xxxxxxxxxx
1
var object = {
2
'key 1': 'item 1',
3
'key 2': 'item 2',
4
'key 3': 'item 3'
5
};
6
7
$.each(object, function(key, item) {
8
console.log(key + ': ' + item);
9
});
each
method with jQuery objects
xxxxxxxxxx
1
var $elements = $('.some-class-name'); // by any css selector
2
3
$elements.each(function(index, element) {
4
console.log(index + ': ' + $(element).text());
5
});
More detailed method description is placed below.
jQuery does not add each
method to array. It is necessary to access it via $.each
call.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
$(document).ready(function() {
10
var array = ['item 1', 'item 2', 'item 3'];
11
12
$.each(array, function(index, item) {
13
console.log(index + ': ' + item);
14
});
15
});
16
17
</script>
18
</body>
19
</html>
jQuery does not add each
method to object. It is necessary to access it via $.each
call.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
$(document).ready(function() {
10
var object = {
11
'key 1': 'item 1',
12
'key 2': 'item 2',
13
'key 3': 'item 3'
14
};
15
16
$.each(object, function(key, item) {
17
console.log(key + ': ' + item);
18
});
19
});
20
21
</script>
22
</body>
23
</html>
jQuery object used on DOM is able to keep many element handles. It is possible to iterate over them with $.prototype.each
method call. Below example shows how to iterate with jQuery for each over html unordered list and print it to browser console. Run below example to see the results.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<ul>
8
<li>item 1</li>
9
<li>item 2</li>
10
<li>item 3</li>
11
</ul>
12
<script>
13
14
$(document).ready(function() {
15
var $elements = $('li'); // all li tags
16
17
$elements.each(function(index, element) {
18
var $element = $(element); // $(this)
19
console.log(index + ': ' + $element.text());
20
});
21
});
22
23
</script>
24
</body>
25
</html>