I have this div:
<div class="mm_vert_container" style="display: block;"></div>
After runing jQuery code I dynamically add div
inside above mm_vert_container
and my code looks like this:
<div class="mm_vert_container" style="display: block;">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<div>F</div>
</div>
So I need to add to every third div
if exists class active so needs to look like this:
<div class="mm_vert_container" style="display: block;">
<div>A</div>
<div>B</div>
<div class="active">C</div>
<div>D</div>
<div>E</div>
<div>F</div>
</div>
I try using jQuery code to add class active to third div:
$(".mm_vert_container div:nth-child(2)").addClass("active");
But it does not add class active to third element. I think that problem is dynamically generated divs and then DOM element using above jQuery code don't see dynamically generated divs and this is why is not work?
Firstly note that indexes when using nth-child
selectors start at 1
, so the 'C' element is at index 3
, not 2
.
To add the class to every third element, use nth-child(3n)
, like this:
$(".mm_vert_container div:nth-child(3n)").addClass("active");
.active {
color: #FFF;
background-color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mm_vert_container" style="display: block;">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<div>F</div>
</div>
Also note that jQuery isn't required here as the nth-child()
selector is well supported in CSS directly:
.mm_vert_container div:nth-child(3n) {
color: #FFF;
background-color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mm_vert_container" style="display: block;">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<div>F</div>
</div>
The latter would be the far better solution because it de-couples the JS logic from the UI, and also means that any child div
elements you add dynamically at a later time in the page lifecycle will automatically be given the styling; ie. you won't need to update the DOM again manually.