Skip to content
Advertisement

How to filter elements and then set condition

First want to filter by class and then change class name :

  <div class="root">
    <div class="col-8 catA filter"></div>        
    <div class="col-4 catB filter"></div>        
    <div class="col-8 catA filter"></div>                
    <div class="col-4 catB filter"></div>                
    <div class="col-8 catA filter"></div>                
    <div class="col-4 catB filter"></div>                
  </div>

I want to filter elements by class name “catB” and set condition :

var myFilterData = $('.filter').filter('.catB');

My condition will be like this :

if (myFilterData.index == even) {
//add New class
}

Is it possible using jquery filter() method ?

Advertisement

Answer

Is this what you mean?

myFilterData.each(function(index) {
    if (! (index % 2)) $(this)
        .addClass("newClass")
        // .removeClass("catB") // Not sure if you also want this
    ;
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement