javascript – Count how many elements with the same class there are with JQuery

Question:

I would like to know how I can count the elements that exist with the same class in an HTML to be able to be with JQuery but with JavaScript also works for me.

Thanks!

Example

div class="hola"
div class="hola"
div class="hola"

A script that says that there are 3 elements with the class "hello".

I've tried?

var divs = document.getElementsByClassName("orange"); 
var numDivs = divs.length; 
var contadorNaranja = 0; 
for(var i = 0; i < numDivs; i++){
  if(divs[i].className == "orange") 
  contadorNaranja++;
}
var puntos1 = contadorNaranja;

document.getElementById("jugador1puntos").innerHTML = "Jugador1: "+puntos1;

Answer:

With javascript

You can use the getElementsByClassName() and print its length

var divs = document.getElementsByClassName("hola").length;
console.log("Hay " + divs + " elementos");
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>

With jQuery

You can use the toArray() that converts the result into an array for its manipulation and you can print its length to know how many elements it has.

var $divs = $(".hola").toArray().length;
console.log("Hay " + $divs + " elementos");
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>
<div class="hola"></div>

If, on the other hand, all you need is to know how many elements exist, you can use $(".hola").length

Scroll to Top