Javascript or Jquery - how to do a Divs class inventory

Asked

Viewed 70 times

2

I have a div of id=colors and inside I have other Ivs with several classes

<div id="cores">
    <div class="azul">conteúdo</div>
    <div class="amarelo">conteúdo</div>
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo </div>       
</div>

I would like to set up a function that would determine how many Ivs with defined class and how many classes there are of each element.

I don’t know if I made myself clear.

Part one solution (Make an array with only class names). I found a solution with find:

    var array_cores = [];

    $("#cores").find('div').each(function(){
        var classe = $(this).attr("class");
        arrayObjetos.push({classe});
    });

    console.log(array_cores);

Generates a result like this;

var array_cores = ["azul", "amarelo", "verde", "azul"];

Now I must count the repetitions

  • The id should be unique on each page.

  • Sorry, I was wrong to write here, are as classes, I will arrange

  • A function that assembles an array of class names and the repetition quantities of that class

  • Ahh I get it....

2 answers

3

You can use the jQuery selector to do this! However, the ids must be unique. So use classes. Snippet below:

console.log($('div#cores div.azul').length, 'azuis')
console.log($('div#cores div.amarelo').length, 'amarelos')
console.log($('div#cores div.verde').length, 'verdes')
.verde {
  color: green
}

.azul {
  color: blue
}

.amarelo {
  color: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cores">
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo</div>
    <div class="amarelo">conteúdo</div>
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo </div>
    <div class="verde">conteúdo</div>       
</div>

The selector $('div#cores div.azul').length takes the blue class Divs that are inside the div with the color id.

EDITED

The snippet below does exactly what you want:

const listaClasses = {}

$('div').each((index,tag) => {
    var classes = $(tag).attr('class') // Busca as classes de cada div
    if(classes != undefined){
      classes.split(' ').map((classe) => { // Separa cada tag e insere no arranjo
         if(classe != undefined){
           listaClasses[classe] = 0 // Define o contador como 0
         }
      })
   }  
})

console.log(listaClasses) // Exibe quais classes existem

const classes = Object.keys(listaClasses)

classes.map(classe => {
  listaClasses[classe] = $(`.${classe}`).length // Grava a quantidade de cada classe
}) // Verifica quais contém cada classe

console.log(listaClasses)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cores">
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo</div>
    <div class="amarelo">conteúdo</div>
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo </div>
    <div class="verde">conteúdo</div>       
</div>

References

  • So, but, then I would need to know the names of the classes that will be on the pages, have to do a function that it scans the page and inform that on this pages there are 10 Divs with the class "x", 5 Divs with the class "Y", without me presquisar by the name of the class?

  • 1

    Well, that’s very specific! The selector needs something set to do the search. You could have an arrangement with all classes, and a for that would search each class within the page

  • If you like, I can add an example to my reply, in case you got confused

  • @Hello, done. Take a look at the snippet I added!

  • Thanks man, I managed with each to make an array only with the names of the classes, now I will make again a each in this array, I will include in the question

  • If my answer has solved your problem, please mark it as a solution! Thank you!

Show 1 more comment

1


You can create an array of objects with the quantities of the classes. An object array is easy after taking the values:

var cores = []; // cria a array;
$("#cores div").each(function(){
   var existe = false; // flag
   for(var x=0; x<cores.length; x++){ // percorre a array pra ver se já existe
      if(Object.keys(cores[x])[0] == this.className){
         existe = true;
         break; // se existe, altero a flag e paro o for
      }
   }
   
   if(!existe){
       var obj = {} // cria o objeto
       obj[this.className] = 1; // cria a chave com valor 1
       cores.push(obj); // adiciona o objeto na array
   }else{
       cores[x][this.className] = cores[x][this.className]+1; // soma mais um na quatidade
   }
});
console.log(cores);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cores">
    <div class="azul">conteúdo</div>
    <div class="amarelo">conteúdo</div>
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo </div>       
    <div class="amarelo">conteúdo</div>
    <div class="verde">conteúdo</div>
    <div class="azul">conteúdo </div>       
    <div class="amarelo">conteúdo</div>
    <div class="azul">conteúdo </div>       
    <div class="branco">conteúdo </div>       
    <div class="azul">conteúdo </div>       
</div>

  • Perfect guy was just what I wanted, thank you, I need to learn to work with objects

  • Cool! I gave an update, I think it looks better.

Browser other questions tagged

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