I would like to know how I can count the elements that there are with the same class in an HTML to be able to be with JQuery but with JavaScript it is also worth it.
Thank you!
Example
div class="hola"
div class="hola"
div class="hola"
A script that says there are 3 elements with 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;
with javascript
You can use the property
getElementsByClassName()
and print its lengthwith jquery
You can use the property
toArray()
that converts the result to an array for manipulation and you can print its length to know how many elements it has.If, on the other hand, all you need is to know how many elements exist, you can use
$(".hola").length
The length property will return the number of elements with that class
$(".hola").length
I hope I have helped
Cheers
What you want to do is very easy. And it can be done perfectly with pure JS. Using jQuery for this would be a regression in my opinion . What I mean is that the code works better and faster with pure JS than with jQuery.
In pure JS there are at least two ways to do it:
getElementsByClassName
using it properlyquerySelectoAll
(it would be the most optimal way, except that compatability is 90%... not bad either).I leave you an example with the two possibilities:
Pretty intuitive, don't you think?