Categories
JavaScript Answers

How to count the number of elements with same class with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *