Check if odd or even children and add class to parent with jQuery

conradical :

How do I check if a list has odd or even LIs and add a class to the UL accordingly.

For example: Count LIs and if they are odd:

<ul class="default-class counted-odd-lis">
  <li></li>
  <li></li>
  <li></li>
</ul>

Or, after counting, they are even:

<ul class="default-class counted-even-lis">
  <li></li>
  <li></li>
</ul>

Here's what I have so far and it does not work.

if ($('ul.default-class > li').length % 2 != 0) {
{
  // Odd
  $('ul.default-class').addClass('counted-odd-lis')
} else {
  // Even
  $('ul.default-class').addClass('counted-even-lis')
}
Rory McCrossan :

The immediate issue in your code is because you have an extra { which is causing a syntax error.

However the logic will only work for a single ul.default-class instance. To make it work for every one on the page you need to loop over them all. This can be done using an implicit loop by providing a function to addClass() which returns the class to be added based on the number of li within each ul. Try this:

$('ul.default-class').addClass(function() {
  return $(this).children('li').length % 2 == 0 ? 'counted-even-lis' : 'counted-odd-lis'
});
.counted-even-lis { color: #C00; }
.counted-odd-lis { color: #0C0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="default-class">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
<ul class="default-class">
  <li>1</li>
  <li>2</li>
</ul>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398458&siteId=1