Reputation: 1071
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.
Upvotes: 3
Views: 1819
Reputation: 11296
With the Each() function:
$(".CCC").each(function(i){
alert(this.id + " is the " + i + "th div with this class");
});
edit:
as requested:
function LoopTroughDivs(selector){
$(selector).each(function(i){
alert(this.id + " is the " + i + "th div with this class");
});
}
Upvotes: 7
Reputation: 32698
// 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'));
Upvotes: 4
Reputation: 12060
Loop each element and put it into your Array.
var yourArray = new Array();
$(".CCC").each(function(index, element){
yourArray[i]=element;
});
Loopthroughdivss(yourArray);
Upvotes: -1
Reputation: 32129
If you want to put it in an array:
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');
}
Note however that the jQuery object itself is an array so you could also do:
for(i=0, x=$('.CCC').length, i<x, i++){
$('.CCC')[i].animate('height', '100px').html("I'm div the "+i+'th div');
}
Upvotes: -1
Reputation: 41391
Looks like this:
LoopThroughDivs($('.CCC'));
Seriously, that's all there is. You can use the jQuery list as an array.
Upvotes: 1