Reputation: 35
I have several div
in my page with class .tg-item-inner
and now I want to give them each random background-color. there is my jquery code:
var color = '#'+Math.floor(Math.random()*16777215).toString(16);
$(".tg-item-inner").css("background-color",color);
that will work. but all the div get one color. I want different color for each one
Upvotes: 0
Views: 184
Reputation: 2253
when setting the a color in hex you need to prepend it with a hash #
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
$(".tg-item-inner").css('background-color', "#" + randomColor);
.tg-item-inner {
height: 50px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tg-item-inner'></div>
Edit: each different colors
$.each($(".tg-item-inner"), function(idx, elem) {
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
$(elem).css('background-color', "#" + randomColor);
});
.tg-item-inner {
display: inline-block;
height: 50px;
width: 50px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tg-item-inner'></div>
<div class='tg-item-inner'></div>
<div class='tg-item-inner'></div>
<div class='tg-item-inner'></div>
Upvotes: 1