Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Class to every second element, count from the first

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?

like image 389
StaXter Avatar asked Dec 10 '22 09:12

StaXter


2 Answers

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');
like image 183
bipin patel Avatar answered Dec 30 '22 21:12

bipin patel


Or JUST this

document.body.querySelectorAll(".timeline li").forEach(function(node,i){
   node.classList.add(i % 2?"even":"odd");
})
like image 44
Dusan Krstic Avatar answered Dec 30 '22 21:12

Dusan Krstic