Sometimes, we want to count the number of elements with same class with JavaScript.
In this article, we’ll look at how to count the number of elements with same class with JavaScript.
How to count the number of elements with same class with JavaScript?
To count the number of elements with same class with JavaScript, we can use the querySelectorAll
method.
For instance, we write
const count = document.querySelectorAll("#main-div .specific-class").length;
to call querySelectorAll
with the selector for the elements with the specific-class
class to get all the elements with that class in a node list.
Then we use the length
property to get the count of the number of elements selected.
Conclusion
To count the number of elements with same class with JavaScript, we can use the querySelectorAll
method.