0

I have code that uses a javascript loop to generate nested divs with various classes. I'm having trouble selecting the nth-child of a certain class amongs those nested divs. After the javascript runs, my html should look like this.

.twoN:nth-of-type(1) {
    background-color: orange;
}

.twoN:nth-child(2){
  background-color:orange;
}
 <div id="grid">
        <div style="width:50px; height:50px; color: white; background-color:blue" class="item oneN">1</div>
        <div style="width:50px; height:50px; color: white; background-color:red" class="item twoN">1</div>
        <div style="width:50px; height:50px; color: white; background-color:green" class="item twoN">1</div>
        <div style="width:50px; height:50px; color: white; background-color:purple" class="item threeN">1</div>
 </div>

I'm trying to select the first or second div with the class "twoN". But for some reason I can only get the Nth-Of-Type selector to work if I use the n variable e.g. nth-of-type(2n+1), but it won't work if I want to select the first child by doing something like nth-of-type(1). I also tried straight up nth-child(1) and that doesn't seem to work neither. I think I'm making some sort of hierarchy mistake.

Tony Martinez
  • 335
  • 3
  • 16
  • 1
    `:nth-of-type` , not `:nth-of-class` - which doesn't exist. Use `.grid > div:nth-of-type(1)` / `.grid > div:nth-of-type(2)` – Vucko Oct 31 '17 at 15:36
  • Ah. So it's not supposed to be used that way.. Any idea how I should do this? Select the nth-child of a certain class. – Tony Martinez Oct 31 '17 at 15:37
  • The problem is that I'm going to have a ton of divs with different class groups underneath the .grid class. So I wanted to be able to go into a certain class group and select the nth-child. Guess I'll just have to structure my dynamically generated html differently to make this easier on me. – Tony Martinez Oct 31 '17 at 15:40
  • 1
    You can select the first item of a class. Regardless on where it is. By using a combination of elements. Say you want first element to have background green, but the rest elements with that class to have background red. You use general sibling connector for that ` .twoN ~ .twoN { red } ` . Now all of them are red. Then use `.twon { green }` . That way first will be green. Rest are red – Mihai T Oct 31 '17 at 15:44

0 Answers0