How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;

document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.


You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size

var parent = document.getElementById("parentId");
var nodesSameClass = parent.getElementsByClassName("test");
console.log(nodesSameClass.length);
<div id="parentId">
  <p class="prueba">hello word1</p>
  <p class="test">hello word2</p>
  <p class="test">hello word3</p>
  <p class="test">hello word4</p>
</div>