Apply random color to class elements individually?

My goal is for every div with class "main" to have a random background color. I have a script that generates random color, but using jquery, I can just apply it to all divs in the class. How can I select a div, apply a color, select the next div in the class, create a new random color, apply it and repeat? Here is my code:

$(document).ready(function() {
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ','
                     + (Math.floor((256-199)*Math.random()) + 200) + ','
                     + (Math.floor((256-199)*Math.random()) + 200) + ')';
    $('.main').css("background-color", hue);
});
+3
source share
3 answers
$(document).ready(function() {
    $('.main').each(function () {
        var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
        $(this).css("background-color", hue);
    });
});
+20
source

The code should be something like this ...

$(document).ready(function() {
                        $('.main').each{ Function(){
                             $(this).css("background-color", hue); };
                        };
                });

Sorry for mistakes. Fixed the worst of them for my own common sense. But another answer beat me.

+1
source
$(document).ready(function() {
  $('.main').each(function(){
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + 
      (Math.floor((256-199)*Math.random()) + 200) + ',' + 
      (Math.floor((256-199)*Math.random()) + 200) + ')';
    $(this).css("background-color", hue);
  }
});
+1

All Articles