Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

$('.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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda