Add/remove class event handler I wrote this if statement event listener to add and remove a class to a couple links based on changed.owl.carousel. However, I know this is not the most DRY method in writing the code and often find myself writing more than is needed. Is there a cleaner way to write this code?

owl.on('changed.owl.carousel', function(event) {
  if ($('.owl-item.active&gt;.item.slide3').length&gt;0) {
    $('#link3').addClass('hover');
  } else if (jQuery('.owl-item.active&gt;.item.slide4').length&gt;0) {
    $('.link').removeClass('hover');
    $('#link4').addClass('hover');
  } else {
    $('.link').removeClass('hover');
  }
})
if ($('.owl-item.active&gt;.item.slide3').length&gt;0) {
  $('#link3').addClass('hover');
} else if (jQuery('.owl-item.active&gt;.item.slide4').length&gt;0) {
  $('.link').removeClass('hover');
  $('#link4').addClass('hover');
} else {
  $('.link').removeClass('hover');
}


I notice the use of both $ and jQuery. Suggesting you use one or the other, but not both. While both are perfectly valid, it's best to keep it consistent.

Also, put a space on both sides of the &gt; for readability. It's not immediately clear that there's actually 2 classes in the selector.

Comparing against 0 is redundant as the number can already double as a boolean. length is a number that's either 0 or a positive integer. Any non-zero number is truthy while 0 is falsy.

I would suggest you avoid IDs. IDs should be unique but nothing prevents you or other code from reusing the same ID. This will lead to problems. For instance, $('#selector') will only return the first of many elements with the same ID.

Without the accompanying HTML, we cannot make assumptions as to how the compare logic works. This is as far as the review goes.