Count the Elements with a specific Class using JS

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

Count the number of Elements with specific Class using JS #

To count the number of elements with a specific class:

  1. Use the querySelectorAll() method to get a collection of the matching elements.
  2. Access the length property on the collection.
  3. The length property will return the number of matching elements.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .blue { background-color: lightblue; } </style> </head> <body> <div id="box"> <span class="blue">Child 1</span> <span class="blue">Child 2</span> </div> <div class="blue">Another</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// โœ… Count all elements with class of blue const countAll = document.querySelectorAll('.blue').length; console.log(countAll); // ๐Ÿ‘‰๏ธ 3 // โœ… Count only elements in the div with `id` = `box`, // that have a class of blue const countInDiv = document.querySelectorAll('#box .blue').length; console.log(countInDiv); // ๐Ÿ‘‰๏ธ 2

In the first example, we used the document.querySelectorAll method to get a collection containing the elements with a class of blue.

The querySelectorAll method takes a string that contains one or more valid CSS selectors as a parameter and returns the matching elements.

Here is an example that uses two selectors to match the elements with classes blue and red.

index.js
const result = document.querySelectorAll('.blue, .red');
The last step is to access the length property on the collection to get the number of matching elements.

Our second example matches the elements inside of the div with id set to box that have the class of blue.

index.js
const countInDiv = document.querySelectorAll( '#box .blue' ).length; console.log(countInDiv); // ๐Ÿ‘‰๏ธ 2

In this example, we narrowed down the results to a specific element.

The selector you pass to the querySelectorAll method can be as specific as necessary.

If no elements match the provided selector, the method returns an empty NodeList, which has a length equal to 0.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee