Question

I am pretty new to jQuery and am looking for a way to count all TDs in one table that have the same background color.

The corresponding TDs do not have a class for the background but look as follows as this is set programmatically in the code before (all other TDs have transparent background).

<td class="clickable search " style="background-color: yellow;">some value</td>

I tried the following but this always returns 0:

alert($("td[style='background-color: yellow']").length);

Thanks for any help, Mike.

Was it helpful?

Solution

You will have to loop through all the TDs and check the background color.

Using grep

alert(
    $.grep($('td'),function(TD){
       return $(TD).css('background-color') == 'rgb(255, 255, 0)';
    }).length
);

Or filter which is better for DOM elements

alert(
    $('td').filter(function(){
    return $(this).css('background-color') == 'rgb(255, 255, 0)';
}).length
);

OTHER TIPS

You want to get all td's and then use jQuery Filter to check if it's got the background color of yellow or not.

DEMO

var yellows = $('td').filter(function(){
    return $(this).css('background-color') === 'rgb(255, 255, 0)';
}).length;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top