jQuery

jQuery Count Elements Examples

When working with different elements of a web page, it might be necessary at times to count the number of elements by using their class. In this article, I am going to share a very easy way to count the number of elements that have the same class using jQuery. The actual code is just 1 line, so it’s super easy to follow along.

How to Count Elements with Class using jQuery – Examples

Let’s assume that we got few divs in our web page and they all have a class of “my_class” applied to them. In such a case, we can count the number of divs easily. Following is the complete code (HTML + jQuery):

Example: Count Elements with Class using jQuery

<html>
<head>
<title>Example</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
.my_class {
	background-color: #DBF0FF;
	border: 1px solid #06F;
}
.my_class2 {
	background-color: #FFDF9D;
	border: 1px solid #F90;
}
.my_class3 {
	background-color: #D7FFD7;
	border: 1px solid #090;
}

</style>
</head>

<body>

<div class="my_class">This is my 1 div</div>

<div class="my_class">This is my 2 div</div>

<div class="my_class">This is my 3 div</div>

<div class="my_class2">This is my 4 div</div>

<div class="my_class2">This is my 5 div</div>

<div class="my_class3">This is my 6 div</div>

<p>
  <input type="submit" name="sbt_count" id="sbt_count" value="Count all divs that have .my_class (blue color background) applied to them ">
</p>

<script type="text/javascript" language="javascript" >

$(document).ready(function(){

	$('#sbt_count').on("click", function(e){		

		alert( $('.my_class').length );

		e.preventDefault();

	});		

});

</script>
</body>
</html>

Simple, isn’t it?

Do you know of any other ways to get the count of elements with specific class using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*