Sunny
Sunny

Reputation: 75

how to ADD class in every to div using loop

This is my structure I want to add odd even class in every two divs so how can I achieve this structure using JavaScript loop i tried everything but i got nothing I am learning JavaScript loop so anyone please help me with this

var i = 0;
$('.CollectionInner__Products .Grid__Cell .ProductItem').each(function(i) {
  var index = 0;
  if (index % 3 == 0) {
    $(this).addClass("odd");
  }
});
<div class="custompsps">
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>

</div>
<div class="custompsps">
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>
  <div class="ProductItem">
  </div>

</div>

I want this structure:

i want this stucture
<div class="custompsps">
  <div class="ProductItem even">
  </div>
  <div class="ProductItem even">
  </div>
  <div class="ProductItem odd">
  </div>
  <div class="ProductItem odd">
  </div>

</div>
<div class="custompsps">
  <div class="ProductItem even">
  </div>
  <div class="ProductItem even">
  </div>
  <div class="ProductItem odd">
  </div>
  <div class="ProductItem odd">
  </div>

</div>

Upvotes: 0

Views: 837

Answers (1)

Ouroborus
Ouroborus

Reputation: 16875

$('.CollectionInner__Products .Grid__Cell .ProductItem').each(function(index, element) {
  $(element).addClass(index & 2 ? "even" : "odd");
});

& is a bitwise "and". index & 2 would be 0 for index 0 and 1, and 2 for index 2 and 3, alternating like this. 0 is falsy and non-0 is truthy. (Your use of "even" and "odd" seem backwards, but I've followed your use.)

jQuery's .each accepts a callback that can take both an index and an element argument.

Upvotes: 1

Related Questions