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
var array = ['item 1', 'item 2', 'item 3'];
$.each(array, function(index, item) {
console.log(index + ': ' + item);
});
each
method with objects
var object = {
'key 1': 'item 1',
'key 2': 'item 2',
'key 3': 'item 3'
};
$.each(object, function(key, item) {
console.log(key + ': ' + item);
});
each
method with jQuery objects
var $elements = $('.some-class-name'); // by any css selector
$elements.each(function(index, element) {
console.log(index + ': ' + $(element).text());
});
More detailed method description is placed below.
1. Iterating over array example
jQuery does not add each
method to array. It is necessary to access it via $.each
call.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
var array = ['item 1', 'item 2', 'item 3'];
$.each(array, function(index, item) {
console.log(index + ': ' + item);
});
});
</script>
</body>
</html>
2. Iterating over object example
jQuery does not add each
method to object. It is necessary to access it via $.each
call.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
var object = {
'key 1': 'item 1',
'key 2': 'item 2',
'key 3': 'item 3'
};
$.each(object, function(key, item) {
console.log(key + ': ' + item);
});
});
</script>
</body>
</html>
3. Iterating over jQuery object example
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.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<script>
$(document).ready(function() {
var $elements = $('li'); // all li tags
$elements.each(function(index, element) {
var $element = $(element); // $(this)
console.log(index + ': ' + $element.text());
});
});
</script>
</body>
</html>