magicspon
magicspon

Reputation: 926

Get number of elements based on data attribute value

Should be a simple thing, but I'm getting no where.

I want to get the number of elements with a given data-attribute value.

I have some html elements with various data-size='values'. Need to get the number of items with each value.

If you look at the code below, I want to get the number of 'p' sizes and 'l' sizes

$('.overview li img').each(function () {

var s = $(this).data('size');

switch (s) {
    case 'p':
        r = 0.66667
        break;
    case 'l':
        r = 1.5
        break;
}

var imgW = $(this).css({
    width: h * r + 'px'
});

})

any help greatly appreciated

cheers dave

Upvotes: 0

Views: 1994

Answers (2)

Tim Edgar
Tim Edgar

Reputation: 2143

You can just create a selector that looks for data-size='p' or data-size='l'

var pCount = $(".overview li img[data-size='p']").length
var lCount = $(".overview li img[data-size='l']").length

Also, you can use the selector to eliminate the switch statement to just loop over elements with data-size='p' or data-size='l'.

Upvotes: 2

Engineer
Engineer

Reputation: 48793

Use some counters:

 var pCount = 0 
     ,lCount = 0;

 $('.overview li img').each(function () {
    //-----------
    case 'p':
        r = 0.66667; 
        pCount++;        //counter of 'p'
        break;
    case 'l':
        r = 1.5;
        lCount++;        //counter of 'l'
        break;
    //----

 });

 console.log( pCount, lCount );

Upvotes: 2

Related Questions