Hugh Chalmers
Hugh Chalmers

Reputation: 153

How to change colour of each element within a class

Let's say I had the following code

<div class="elements">
   <span></span>
   <span></span>
   <span></span>
</div>
<style>
   .span {
      background-color: red;
      width: 50px;
      height: 50px;
   }
</style>

This would produce 3 red squares within the elements div. Would there be a way for me to assign each span element a random colour independent of each other? So when I load the page, one might be yellow, another blue, and the last could be red

Upvotes: 1

Views: 326

Answers (2)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17570

to random assign you can use javascript

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

document.querySelectorAll('span').forEach(x=>{
 x.style.color= getRandomColor();
})
<div class="elements">
   <span>a</span>
   <span>b</span>
   <span>c</span>
</div>
<style>
   span {
      width: 50px;
      height: 50px;
   }
</style>

Upvotes: 3

dale landry
dale landry

Reputation: 8600

Use foreach and an array to define your background colors run a function to shuffle the array and find a unique color

//get the element list using the tag and parent class
let spans = document.querySelectorAll('.elements span');
//assign colors to an array
let colors = ['red', 'green', 'blue', 'purple', 'orange', 'pink', 'yellow', 'teal']
const randomElement = colors[Math.floor(Math.random() * colors.length)];
//shuffle the array of colors
function* shuffle(colors) {
    var i = colors.length;
    //run while loop and decrement the array colors 
    while (i--) {
        //splice using a random number wihtin the array to find unique values
        yield colors.splice(Math.floor(Math.random() * (i+1)), 1)[0];
    }
}
//redefine the color array by shuffling it
var ranCols = shuffle(colors);


//iterate over the element list
spans.forEach(function(value) {
  //Assign the style backgroundColor to the element/s
  value.style.backgroundColor = ranCols.next().value;
})
.span {
  background-color: red;
  width: 50px;
  height: 50px;
}
<div class="elements">
  <span>Test</span>
  <span>Test</span>
  <span>Test</span>
</div>

Upvotes: 0

Related Questions