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 "

Генератор случайных чисел c rand
Возведение в степень с: правила, примеры, алгоритмы
Программирование на языке C: полное руководство
Конвертер JPG в SVG
Объединение данных с помощью c union
Range в Python: работа с последовательностями чисел
Base C: создание, использование и оптимизация баз данных
FindIndex - ваш надежный помощник для поиска и индексации
Python или
Оценка точности в scikit-learn с помощью sklearn accuracy score