ForEach в jQuery: удобный способ перебора элементов

Looping with foreach in jQuery

Looping with foreach in jQuery

Example 1: foreach loop for an array

Let's say we have the following array:


var fruits = ['apple', 'banana', 'pear'];
  

We want to display each element of this array using a foreach loop. To do this, we can write the following code:


$.each(fruits, function(index, value) {
  console.log(index + ': ' + value);
});
  

The output of this code will be the following:


0: apple
1: banana
2: pear
  

Example 2: foreach loop for a list of elements

Let's say we have the following HTML list:


  • apple
  • banana
  • pear

We want to add the "active" class to all the elements of this list using a foreach loop. We can do this with the following code:


$('#fruitsList li').each(function(index, element) {
  $(element).addClass('active');
});
  

Each item in the list will now have the "active" class.

Therefore, the foreach loop in jQuery is a powerful and convenient tool for iterating over collections of elements. It allows easy iteration over arrays, lists, and objects, applying specific actions to each item. This is particularly useful when working with DOM elements and manipulating them.

I hope these examples have helped you understand the usage of the foreach loop in jQuery better. If you have any further questions, feel free to ask!

Похожие вопросы на: "foreach jquery "

Биржевой API Binance: возможности, документация и интеграция
Типedef в C: объявление пользовательского типа данных
Восстановление баз данных PostgreSQL с помощью pg_restore
Random Python 3
Метод charAt в JavaScript: использование и примеры
Тема x0: основные аспекты и интересные факты
Найдите индекс с помощью JavaScript
Создание http сервера на Python
Високосный год: объяснение и факты
Работа с VBA массивами: примеры и инструкции