最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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>

发布评论

评论列表(0)

  1. 暂无评论