4 4 Votes

jQuery: Count elements with a specific class

Question by NetLabel | 08/01/2013 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

Stefan Trost

Show Profile | Message
Avatar
5Best Answer
7 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.
10/01/2013 at 17:48

ReplyPositive Negative
Reply

Related Topics

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 articles on askingbox.com. How to do.