I have a list where I want to add classes to every second element, counting from the first one.
Here's my list
<ul class="timeline">
<span class="topbullet"></span>
<li></li>
<li></li>
<div class="clearfix"></div>
<li></li>
<li></li>
<div class="clearfix"></div>
<li></li>
<li></li>
<div class="clearfix"></div>
<li></li>
<li></li>
<div class="clearfix"></div>
<li></li>
<li></li>
<div class="clearfix"></div>
</ul>
I want to have it like this:
<ul class="timeline">
<span class="topbullet"></span>
<li class="odd"></li>
<li class="even"></li>
<div class="clearfix"></div>
<li class="odd"></li>
<li class="even"></li>
<div class="clearfix"></div>
<li class="odd"></li>
<li class="even"></li>
<div class="clearfix"></div>
<li class="odd"></li>
<li class="even"></li>
<div class="clearfix"></div>
<li class="odd"></li>
<li class="even"></li>
<div class="clearfix"></div>
</ul>
Here's my jQuery Code
$(".timeline li:nth-of-type(2n)").addClass('even');
It's no problem to add the 'even' classes, but how to add the 'odd' classes? Which selector should I use to count from the first list element?
You can use odd and even selector of jquery like this
$( ".timeline li:odd" ).addClass('odd');
$( ".timeline li:even" ).addClass('even');
For your requirement you need to first odd and than even so you change this jquery like this
$( ".timeline li:odd" ).addClass('even');
$( ".timeline li:even" ).addClass('odd');
Or JUST this
document.body.querySelectorAll(".timeline li").forEach(function(node,i){
node.classList.add(i % 2?"even":"odd");
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With