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.
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");
});
}
// 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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With