Q:

Apply a random class to an element

Possible Duplicate:
Apply a random class to every element specified 

Is it possible to get all 'a' elements on a page and apply the class either '.pink', '.blue', or '.yellow' RANDOMLY to every a element with javascript?  I want to have different colored links on my page but equally randomized.  I don't have a clue how I'd do this so I don't have any scripts to provide. 

A:

When you use jQuery as stated in your tags, this is a possible solution:
// when document is loaded
$(document).ready(function () {

    // set classes
    var classes     = new Array ('pink', 'blue', 'green');

    // calculate length once, as this will never change
    var length      = classes.length;

    // select all a-tags
    var links       = $('a');

    // loop through all a-tags and apply color randomly
    $.each( links, function(key, value) {
        // get random value/class-name from array and add it using the addClass function
        $(value).addClass( classes[ Math.floor ( Math.random() * length ) ] );
    });

});

The comments should make clear what it does. 
Try it

