1

I have HTML in this structure:

<ul class="list">
    <li>name</li>
    <li>name</li>
    <li>name</li>
    <li>name</li>
</ul>

I want check if the count of li elements is even. How can I use this in an if statement?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Muhamed
  • 876
  • 8
  • 11
  • 1
    Have a look at [How can I count the number of children?](http://stackoverflow.com/questions/3546659/how-can-i-count-the-number-of-children) and [Testing whether a value is odd or even](http://stackoverflow.com/questions/6211613/testing-whether-a-value-is-odd-or-even). – Felix Kling Dec 08 '11 at 11:23

2 Answers2

6
if ($('ul.list > li').length %2 != 0){
    // Odd
}else{
    // Even
}
472084
  • 17,666
  • 10
  • 63
  • 81
3
if ($('ul>li').length % 2 == 0)
{
   // do if even
}
else
{
   // do if not
}

Also, if you need to apply to the even items something you can use:

$('ul>li:even').addClass('even')

Or odd:

$('ul>li:odd').addClass('even')
Samich
  • 29,157
  • 6
  • 68
  • 77