I have a collection of child div's inside the parent div,the child div's are generated dynamically and all has the same class name.
My question is how to apply different background color for each child div using jquery sample code below
<div id="someid">
<div class="bar">...</div>
<div class="bar">...</div>
<div class="bar">...</div>
<div class="bar">...</div>
<div class="bar">...</div>
</div>
Here i want to apply different background color for each child div( class="bars")
Thanks in advance.
Something like this:
var colors = ["f00", "0f0", "00f", "ff0", "0ff", "f0f"];
$('#someid .bar').each(function(i) {
$(this).css('background-color', '#'+colors[i % colors.length]);
});
To produce random colors, you can use this:
function randomColor() {
return 'rgb('+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+')'
}
$('#someid .bar').each(function(i) {
$(this).css('background-color', randomColor());
});
Demo:
http://jsbin.com/eqoyi4
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