35 Votes

jQuery: Count elements with a specific class

Question by NetLabel | 2013-01-08 at 23:00

I would like to count all elements on my page having assigned a specific class with jQuery. So, for example:

<span class="a"></span>
<span class="b"></span>
<span class="a"></span>

Here, the result for all elements with the class "a" should be 2 and for all elements with the class "b", it should be 1.

ReplyPositiveNegative
5Best Answer7 Votes

Each selector in jQuery has the property "length". Thus you can query quickly, how many items of a particular class are available:

var counta = $(".a").length;
var countb = $(".b").length;

This can be combined with any other selectors, for example, to count only the elements that are in a DIV of a specific ID:

var countc = $("#c.cclass").length;
var countd = $("div#c.cclass").length;

The first line counts the elements with the class "cclass" in the element with the ID "c". The second line counts all elements with the class "cclass" in the element with the ID "c" in a DIV container.
2013-01-10 at 17:48

ReplyPositive Negative
Reply

Related Topics

jQuery: Show and hide elements

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.