Adding an "alt" class to every third element in jQuery

I need to add an “alt” class to every third div of a certain class. Could someone please show me how to do this. I’d appreciate it if you could use jQuery to do it.


Your syntax would look something like: $(‘.myClass’).addClass(‘alt’);

Yes, I know that much, but what I’m having trouble figuring out (mostly because I know almost zip about JavaScript) is how to tell jQuery to only apply that to every 3rd element.

Create a counter. I dunno jQuery, but:

for(var i = document.getElementsByTagName(“div”), x = 0, y = i.length, z = 0; x < y; x ++) {
if(i.className == “whatever”) {// use a simple workaround if it has multiple classes
z ++;
if(count % 3 == 0) // Move this above z ++ if you want it to run on the very first DIV
i.alt = “whatever”;

I am a beginner but I think you can use something like

          i = 1
          $('#mediummap area').each(function(j){
               i = i + 1;
               if (i == 3) {
                      // add class
                      i = 0;

Thanks so much for the help… I got what I needed.

Sorry about the delay, my Wifi died yesterday… The most efficient method would be the following:
var allTargetClasses = $(‘.myClass’);
var i = 2;
var iMax = allTargetClasses.length;
while(i < iMax) {
i += 3;

With this method you do not cycle through each node, but only the required ones, therefore your script will execute faster. Also, while loops execute much faster than a jQuery Each, and are tailored for cases such as yours.

On the whole, this is the cleanest possible way to acheive what you want

You guys have all forgotten that jQuery supports pretty advanced CSS selectors: