Reputation: 1497
I have some divs with the same class (class="myDiv"
) inside a .container
and these divs can be basically anywhere inside the container...
I want to target all the divs which have the class .myDiv
and apply css like this:
My current approach looks like this: jsFiddle (snippet copy below)
.myDiv:nth-child(1){color:red;}
.myDiv:nth-child(2){color:green;}
.myDiv:nth-child(3){color:aqua;}
.myDiv:nth-child(4){color:orange;}
.myDiv:nth-child(5){color:pink;}
<div class="container">
<table>
<tr>
<td><div class="myDiv">One</div></td>
<td>Normal text</td>
<td>Normal text</td>
<td>Normal text</td>
<td>
<table>
<tr>
<td><div class="myDiv">Two</div></td>
</tr>
</table>
</td>
<td><div class="myDiv">Three</div></td>
<td><div class="myDiv">Four</div></td>
</tr>
</table>
<div class="myDiv">Five</div>
</div>
Expected result:
Actual result:
Upvotes: 3
Views: 43
Reputation: 13209
As noted in comment, nth-child
is not the "nth occurrence", but instead based on specific child of parent element.
However, you can accomplish a similar effect with basic javascript if you revise your CSS to this:
.myDiv1{color:red;}
.myDiv2{color:green;}
.myDiv3{color:aqua;}
.myDiv4{color:orange;}
.myDiv5{color:pink;}
Then, the following simple javascript will assign the nth occurrence.
var divs = document.getElementsByClassName("myDiv");
for (var i = 0; i < divs.length; i++)
divs[i].classList.add('myDiv'+(i+1));
Upvotes: 3