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.
+6
A:
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");
});
}
Thomas Stock
2009-05-06 11:18:14
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
Hitz
2009-05-06 11:25:07
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
Thomas Stock
2009-05-06 11:38:38
Thanks for the solution
Hitz
2009-05-06 11:44:40
+1
A:
Looks like this:
LoopThroughDivs($('.CCC'));
Seriously, that's all there is. You can use the jQuery list as an array.
altCognito
2009-05-06 11:27:40
A:
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');
}
Pim Jager
2009-05-06 11:32:46
A:
Loop each element and put it into your Array.
var yourArray = new Array();
$(".CCC").each(function(index, element){
yourArray[i]=element;
});
Loopthroughdivss(yourArray);
Luis Melgratti
2009-05-06 11:33:13
+2
A:
// 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'));
Garry Shutler
2009-05-06 11:34:19
Any idea how to reverse loop using your code..like pick the last div.ccc first ?
Hitz
2009-05-06 11:56:25
Appears it's not in the core but there's many plugins that do it like http://lab.arc90.com/2008/05/jquery_reverse_order_plugin.php
Garry Shutler
2009-05-06 11:59:08
Moreover how do you propose using this plugin..like this $('div.CCC')reverseOrder.each(function() ...?
Hitz
2009-05-06 12:12:14
That line instead of looping reverse, actually rotates the div's physcially..any other suggestion?
Hitz
2009-05-06 12:21:39