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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.