Take a look at this example:
var contador = 0;
$('div').each(function() {
if ($(this).hasClass('box')) {
contador++;
this.innerHTML = contador;
if (contador % 2 == 0) this.style.color = 'blue'; // ou outro código que precises
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div>Eu não tenho a classe box</div>
<div>Eu não tenho a classe box</div>
<div class="box"></div>
This code only counts the elements that have the class you want and using % 2 == 0
you know when the count has zero rest divided by 2.
If you want to "go two by two" you can do it like that too:
$('.box:nth-of-type(2n)').each(function(i) {
this.style.color = 'blue'; // ou outro código que precises
});
If you want to do things with CSS you better use nth-of-type(2n)
. But that wasn’t clear from your question.
I didn’t put that part in the question. What I’m going to do is add another class next to the box class in html.
– Carlos Henrique
@Caiquesouza in this case on the line
if (contador % 2 == 0)
you can continue with$(this).addClass('novaClasse');
– Sergio
@Caiquesouza I added another more compact variation, if useful.
– Sergio