Home > Mobile >  Migrating :odd selector behaviour after jQuery Depreciation
Migrating :odd selector behaviour after jQuery Depreciation

Time:02-10

I am having issues migrating the last bit of our code to exit depreciation. We use jQuery 3.6, and since jQuery 3.4 the :odd selector is depreciated.

As of jQuery 3.4, the :odd pseudo-class is deprecated. Remove it from your selectors and filter the results later using .odd() (available in jQuery 3.5.0 or newer).

However, it appears to be very difficult to retain the background color for every 3rd row.

.divGrey {
  background-color: #c0c0c0;
}
$('.container').filter(function () {
  return $(this).children().length === 3;
}).filter(':odd').addClass('divGrey'); // :odd Depreciated

I can do .odd().addClass('divGrey') but I lose the background I want to retain for every third child. How can I do this? Do I need to remove filter function?

Any help appreciated - thanks!

CodePudding user response:

To do what you require you can use the index argument provided to a function handler in filter() and return a boolean value to state if the element's index is even or odd, like this:

$('.container').filter(i => i % 2).addClass('divGrey');
.divGrey {
  background-color: #c0c0c0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >0</div>
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>

Note that I removed the first filter() call as it wasn't relevant to the question.

  • Related