javascript - How to style and Array object in CSS - Stack Overflow

how would I be able to take each array and style them differently in CSS NOT in JS ?count = ['1�

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
Add a ment  | 

2 Answers 2

Reset to default 5

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>

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742394742a4435716.html

相关推荐

  • javascript - How to style and Array object in CSS - Stack Overflow

    how would I be able to take each array and style them differently in CSS NOT in JS ?count = ['1�

    18小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信