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>

2
  • what are the different CSS classes you want to apply ? Commented Feb 2, 2017 at 21:06
  • 1
    use nth-child..... Commented Feb 2, 2017 at 21:06

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

3

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>

3 Comments

@ЕгорКротенко that's one solution, this is another.
Thanks both answers are get !! IS their away that I could add you guy to a friends list ? Im really new to JS / coding need some Friends lol
This site doesn't do "friends". It's the quality of the individual answers that counts, not the persons who post them. That's only natural: if you like one answer by someone, that doesn't necessarily mean you'll like all answers by that person. So the identify of the poster is unimportant. With the exception of Jon Skeet of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.