JQuery loop

I have a couple of Divs with class = 'CCC'. I want to take all these divs in an array using jQuery and then skip the array. How to do it.

+3
source share
5 answers
// get an array of the divs (will act like one anyway)
var divs = $('div.CCC');

// do something for each div
divs.each(function() {
   // this refers to the current div as we loop through       
   doSomethingWith(this);
});

// or call your method on the array
LoopThroughDivs(divs);

Alternatively, they can be written as a single statement (if you want to make only one of them):

$('div.CCC').each(function() {
   // this refers to the current div as we loop through       
   doSomethingWith(this);
});

LoopThroughDivs($('div.CCC'));
+4
source

With Every () function:

$(".CCC").each(function(i){
   alert(this.id + " is the " + i + "th div with this class");
 });

http://docs.jquery.com/Each

change

upon request:

function LoopTroughDivs(selector){
  $(selector).each(function(i){
   alert(this.id + " is the " + i + "th div with this class");
 });
}
+7
source

:

LoopThroughDivs($('.CCC'));
, . jQuery .
+1

:

 var divArray = new Array();
 $('.CCC').each( function() { divArray.push(this); }); //add each div to array
 //loop over array
 for(i=0, x=divArray.length, i<x, i++){
  //divArray[i] refers to dom object, so you need to use a jquery wrapper
  //for the jquery functions: 
  $(divArray[i]).animate('height', '100px').html("I'm div the "+i+'th div');
 }

, jQuery , :

 for(i=0, x=$('.CCC').length, i<x, i++){
  $('.CCC')[i].animate('height', '100px').html("I'm div the "+i+'th div');
 }
-1

.

var yourArray = new Array();
$(".CCC").each(function(index, element){
    yourArray[i]=element;
 });

Loopthroughdivss(yourArray);
-1

Source: https://habr.com/ru/post/1707754/


All Articles