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>
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>
Share
Improve this question
edited Feb 2, 2017 at 21:08
Scott Marcus
65.9k6 gold badges53 silver badges80 bronze badges
asked Feb 2, 2017 at 21:04
cordcord
751 gold badge2 silver badges8 bronze badges
2
- what are the different CSS classes you want to apply ? – Abhinav Galodha Commented Feb 2, 2017 at 21:06
- 1 use nth-child..... – Егор Кротенко Commented Feb 2, 2017 at 21:06
2 Answers
Reset to default 5Using 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>
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>