cord
cord

Reputation: 75

How to style and Array object in CSS

how would I be able to take each array and style them differently in CSS NOT in JS ?

count = ['1','2','3','4'];
container = document.getElementById('itemsContainer');
  for(i = 0; i < count.length; i++){
    container.innerHTML+='<div class="items"></div>';
  }

var square= document.getElementsByClassName('items')[2];
square.style.backgroundColor='red';
.items{
  margin-top:10px;
  width:20px;
  height:20px;
  background:gold;
<div id="itemsContainer"></div>

Upvotes: 1

Views: 5424

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65808

Using the nth-child() pseudo-class selector, we can differentiate between the elements without having any unique identifiers on the elements themselves. We don't even need an array.

container = document.getElementById('itemsContainer');

for(i = 0; i < 6; i++){
    container.innerHTML+='<div class="items"></div>';
}
.items{
  margin-top:10px;
  width:20px;
  height:20px;
  background:gray;
 }

.items:nth-child(1){ background:gold; }
.items:nth-child(2){ background:green; }
.items:nth-child(3){ background:red; }
.items:nth-child(4){ background:blue; }
<div id="itemsContainer"></div>

Upvotes: 5

Michael Coker
Michael Coker

Reputation: 53664

Change your JS to create a unique class for each item, then in your CSS, reference those classes

count = ['1','2','3','4'];
container = document.getElementById('itemsContainer');
  for(i = 0; i < count.length; i++){
    container.innerHTML+='<div class="items item' + i + '"></div>';
  }
.items{
  margin-top:10px;
  width:20px;
  height:20px;
  background:gold;}

.item1 {
  background: green;
}
.item2 {
  background: blue;  
}
<div id="itemsContainer"></div>

Upvotes: 3

Related Questions