Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery loop

Tags:

jquery

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

like image 944
Hitz Avatar asked Aug 03 '26 11:08

Hitz


2 Answers

With the Each() function:

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

http://docs.jquery.com/Each

edit:

as requested:

function LoopTroughDivs(selector){
  $(selector).each(function(i){
   alert(this.id + " is the " + i + "th div with this class");
 });
}
like image 139
Thomas Stock Avatar answered Aug 07 '26 10:08

Thomas Stock


// 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, these could be written as a single statement (if you only want to do one of them):

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

LoopThroughDivs($('div.CCC'));
like image 32
Garry Shutler Avatar answered Aug 07 '26 10:08

Garry Shutler