Catch interspersed CSS classes using jQuery

Asked

Viewed 162 times

3

I need to know how to get CSS classes interspersed. Because I’m going to 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 of 2 in 2, 3 in 3 and so on?

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

2 answers

2

If I understand the question correctly, all you have to do is touch the increment (interval) of a for/while cycle. In this case I’ll do it 2 by 2. You can do it like 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>
<div id="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 on .box to see how it works. No need.

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>
<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
});

jsFiddle: https://jsfiddle.net/9zz42g8g/

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.

  • 1

    @Caiquesouza in this case on the line if (contador % 2 == 0) you can continue with $(this).addClass('novaClasse');

  • 1

    @Caiquesouza I added another more compact variation, if useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.