Add class on Odd or Even items

I’m trying to add a class to page children listed on the homepage. I like to give a class to every odd item. I tried this but this checks only if the full amount of children are odd or even. Any idea how I can solve this?

<?php if($child->isOdd()) : ?><?php endif ?>

If you only need this for styling purposes, use CSS nth-child(), there is no isOdd() etc page method.

Hmm, that is not going to work. I need to add some data-attributes to odd classes. Thanks for the info! I will figure something out.

That’s why I was asking. You can check if $page->indexof($collection) is even or odd:

Example:

$children = page('notes')->children()->listed();
foreach ($children as $child) {
  if (($child->indexOf($children) + 1) % 2) {
    echo $child->title() . 'is odd';
  } else {
    echo $child->title() . 'is even';
  }
}

Note that because the index starts at 0, we add 1 to the index. If it’s not important and you just want to get every second, you can remove that.

3 Likes

This is perfect! Thanks again @texnixe