n00b0101
n00b0101

Reputation: 6893

jquery - count divs with ids in an array?

Not sure how to do this with jquery, but I'm trying to return a count of the number of divs that have specific classes...

<div id="main">
<div class="contact">Data</div>
<div class="margin">Margin</div>
<div class="contact">Data</div>
<div class="break">Break</div>
<div class="break">Breaker</div>
<div class="nap">Nap</div>
</div>

And, I want to return a count of divs with a class of contact, break, and nap, so that the count returns: 5... In reality, there will be about 30 classes, and I'd rather not have to write out an if statement for each one... So, hopefully there's a way to build an array and just check to see if the class is in the array?

Upvotes: 1

Views: 5596

Answers (3)

Zia
Zia

Reputation: 2710

Jonathan Sampson has the best answer, though instead of:

var count = $("div.contact, div.break, div.nap", "#main").length;

I would do this:

for each div you want in the array, add a grouping class:

<div id="main">
    <div class="contact grouped">Data</div>
    <div class="margin">Margin</div>
    <div class="contact grouped">Data</div>
    <div class="break grouped">Break</div>
    <div class="break grouped">Breaker</div>
    <div class="nap grouped">Nap</div>
</div>

Then use this js.

var count = $("#main .grouped").length;

This way, you can add or remove elements in only one place and gives you more control over exceptions and which elements are in the group.

Upvotes: 0

Sampson
Sampson

Reputation: 268344

var count = $("div.contact, div.break, div.nap", "#main").length;

As stated in the comments, if you need this to be based off of an array:

var classes = ["div.contact", "div.break", "div.nap"];
var count   = $(classes.join(", "), "#main").length;

Upvotes: 6

Scott Evernden
Scott Evernden

Reputation: 39926

if it's important to use an array:

var classes = ['contact', 'break', 'nap'];
//...
var count = 0;
$.each(classes, function(i, c) { count += $('div.' + c, '#main').length; });
alert(count);

Upvotes: 1

Related Questions