ntgCleaner
ntgCleaner

Reputation: 5985

jQuery getting element by class name with one of two classes in a variable

Not sure how to word this question... I have a script that does an each loop for every nth element.
I have this as a variable: var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')'); then I do a .each with it nthCard.each(function(i){...}

After the each, I need to find out how many of nthCards have the class .featured.

The html is set up like so:

<div class="card"></div>
<div class="card featured"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card featured"></div>

Assuming this is the each statement, I need to find how many of these cards are also featured.

I tried something like this: console.log(nthCard.find('.featured').length); and also console.log(nthCard.hasClass('.featured').length); but the former returns 0 and the later returns undefined.

Here's the truncated code:

function placeCard(col){
    var i = 0;
    for(i=1; i<= col; i++){
        var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
        nthCard.each(function(idx){
            //do some code
        });
        console.log(nthCard.find('.featured').length);//I need to return the number of featured cards here.
    }
}

Upvotes: 1

Views: 207

Answers (3)

rjmunro
rjmunro

Reputation: 28056

Why not count them while you are in the each loop?

function placeCard(col){
    var i = 0;
    for(i=1; i<= col; i++){
        var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
        var count = 0;
        nthCard.each(function(idx, card){
            //do some code
            if ($(card).hasClass('featured')) {
                count += 1;
            }
        });
        console.log(count);//I need to return the number of featured cards here.
    }
}

Or, more optimally:

function placeCard(col){
    var i = 0;
    for(i=1; i<= col; i++){
        var nthCard = $('.card:nth-child(' + col + 'n+' + i + ')');
        var count = 0;
        nthCard.each(function(idx, card){
            //do some code
            if (card.className === 'card featured') {
                count += 1;
            }
        });
        console.log(count);//I need to return the number of featured cards here.
    }
}

Upvotes: 1

DeweyOx
DeweyOx

Reputation: 719

Try:

console.log(nthCard.hasClass('featured'));

Upvotes: 1

Blender
Blender

Reputation: 298056

filter the matched elements:

var number = nthCard.filter('.featured').length;

Upvotes: 4

Related Questions