Catching CSS classes interspersed using jQuery

3

I need to know how to get interspersed CSS classes. Well I'm going to do a loop and I need to get the classes in a certain number.

The code is as follows:

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

How do I get these classes with jQuery 2 in 2, 3 in 3 and so on?

Making it clear that I need to count by classes, not by elements.

    
asked by anonymous 05.06.2016 / 22:46

2 answers

1

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><divclass="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 this too:

$('.box:nth-of-type(2n)').each(function(i) {
    this.style.color = 'blue'; // ou outro código que precises
});

jsFiddle: link

If you want to do things with CSS, it's best to use nth-of-type(2n) . But that was not clear from your question.

    
06.06.2016 / 00:01
2

If I understood the question well, you only have to deal with the incrementing (interval) of a for / while loop. In this case I will do it in 2's. You can do this:

//var elementos = document.getElementsByClassName('box'); // Sem jquery
var elementos = $('.box'); // com jquery
var countElementos = elementos.length; // num de elementos com a classe
var intervalo = 2; // aqui decides o intervalo
var comeco = 0; // aqui decides em qual queres começar, neste caso começamos na primeira .box

for(var i = comeco; i < countElementos; i += intervalo) {
	alert('.box num ' +elementos[i].id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="1" class='box'></div>
<div id="2" class='box'></div>
<div id="3" class='box'></div>
<div id="4" class='box'></div>
<div id="5" class='box'></div>

Note that I only put ids in .box to see how it works. They are not accurate.

    
05.06.2016 / 22:58