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.
5 Answers
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");
});
}
2 Comments
Hitz
As I said, I first want to take it in an array. I will thenbe passing that array to a function called LoopThroughDivss like this: Loopthroughdivss(divsarray); Please tell me solution for that
Thomas Stock
well that wasn't so clear in your question.. my solution can easily be used in a function that gets passed a parameter with the jquery selector. I'll edit my answer
// 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'));
6 Comments
Hitz
Any idea how to reverse loop using your code..like pick the last div.ccc first ?
Garry Shutler
$('div.CCC').reverse() I think
Garry Shutler
Appears it's not in the core but there's many plugins that do it like lab.arc90.com/2008/05/jquery_reverse_order_plugin.php
Hitz
Thanks..Is there any other way other than using one more plugin?
Hitz
Moreover how do you propose using this plugin..like this $('div.CCC')reverseOrder.each(function() ...?
|
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');
}
1 Comment
balexandre
why using a 200 ft truck to carry a ball?