function to count Divs quantity

Asked

Viewed 2,126 times

3

I need to create a function to check the amount of Divs on the screen and insert a class within the fourth for example. These Divs are created dynamically.

  • 1

    console.log(document.querySelectorAll('div').length); It will count the total of Divs you have in the DOM. Your doubt is a little confused, for example you will always insert in the 4 div you find in the document, ie is fixed? Is there a button or event that will trigger the class insertion?

  • See functioned Fiddle

  • "On the screen" you say in the full page or only in the visible part of the page?

5 answers

8

For the problem you presented, it is not necessary to use Javascript. The increment in the count of elements can be done through the property counter-increment and the sum of the elements can be done with the function counter().

Get the fourth element, can be done with pseudo classes nth-child or nth-of-type.

/* Todo elemento <div> irá incrementar o contador "divnumber". */
div {
  counter-increment: divnumber
}

/* "counter" irá pegar o valor de "divnumber". */
span::after {
  content: 'Existem ' counter(divnumber) ' divs.'
}

/* ntd-child irá pegar o quarto elemento <div>. */
div:nth-child(4) {
  color: red
}
<div>div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>


<br><br>
<span></span>

4


To select ALL as divs you can simply use the selector with:

var divs = $('div'); // Armazena um `NodeList` com todos os elementos

Amount:

var qtd = divs.length; // Numero inteiro da quantidade de divs

To change the div desired you can use the function addClass or css of jquery, remember that the count of divs starts from 0 so if you want to change for example the color of the fourth font div would look like this:

$(divs[3]).addClass('red');

var divs = $('div');
var length = divs.length;

$(divs[3]).addClass('red');
// Ou
$(divs[3]).css({
  color: 'red'
});
.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>10</div>
<div>11</div>
<div>12</div>

To change the divs with repetition (from 4 to 4) you can use the selector css nth-child(xn+x), which works as follows:

$('div:nth-child(4n+0)').css({
    color: 'red'
});

Explanation:

nth-child selects the number of the div that you want for example :nth-child(1), select the first element and so on, if you use as in the example above it will use the following logic:

:nth-child(4n... Jump four by four.

...+0) starting from 0

You can test by changing the numbers: :nth-child(2n+1) "Skip 2 by 2 starting from the first"

  • Thank you so much for your help.

  • Need to complicate a little, as I can do for this function with the Divs and 4 in 4 she add a class?

  • @carlosgiovanicasilo I suggest you do this with css pure, would be easier, but I will add the in the answer.

  • Caleu even for the help, thank you very much.

1

I set the code to count the Ivs and only fill in if it’s above 3. I take all Divs containing class’d' for count and modification.

jQuery(document).ready(function(){
      if(jQuery('.d').length > 3){
        jQuery(jQuery('.d')[3]).addClass('red');
      } else{
        alert('A quantidade de divs na tela é inferior a 4');
      }
    })
.red{
          background: red;
          width: 200px;
          height: 200px;
          float:left;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="d"></div>
<div class="d"></div>
<div class="d"></div>
<div class="d"></div>
<div class="d"></div>

  • 1

    Your function is not checking the amount of existing Ivs. You can reverse the negative.

  • @Magichat changed made.

0

 $(document).ready(function() 
            {
                $('div').each(function(i, value)
                    {
                        if(i ==3)
                        {
                            $(value).addClass('teste');
                        }
                    });

            });

0

As the question did not specify the use of Jquery, I think it fits a solution with Javascript Vanilla:

// Obter a quantidade de divs
var quantidadeDivs = document.getElementsByTagName("div").length;

// Obter array com todas as divs da página
var divs = document.getElementsByTagName("div");

// Adicionando a classe vermelho na quarta div
divs[3].classList.add('vermelho');

Browser other questions tagged

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