views:

680

answers:

4

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?

+4  A: 
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;
Jonathan Sampson
+1. And if it has to be an array, you could easily build the selector from an array using join. This is the fastest way.
Chetan Sastry
+1  A: 

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);
Scott Evernden
A: 

strong text***

`

    -


`


5555
A: 

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.

JSD