views:

117

answers:

5

I'm trying to use jQuery to find the number of divs that are both visible, and have a background color of Green.

(Normally I'd just add a class to the div, style it green, and check for that class in jQuery but in this instance, I can't actually change the markup of the page itself in any way)

I currently have the visible div part working as :

if(  // if there are more than one visible div 
    $('div.progressContainer:visible').length > 0   
){

I'd like to throw some kind of "and background color is green" selector in there.

// not legit javascript
if(  // if there are more than one visible div, and its color is green 
    $('div.progressContainer:visible[background-color:green]').length > 0   
){

Is it possible to do this?

+3  A: 

jQuery does not have style-based selectors (other than :visible), so you can't do that.

You can use filter instead:

$('div.progressContainer:visible').filter(function() {
    return $(this).css('background-color') === 'green';
})

Note that it won't match background-color:#0F0.

SLaks
A: 

you could do this:

if($('div.progressContainer:visible').css('background-color') == 'green'){
   //should equal true, if it's green
}
Oscar Godson
+2  A: 

You can use filter to fine tune what you're selecting like this:

$('div.progressContainer:visible').filter(function(){
   return $(this).css('background-color') == 'green';
});
wsanville
+4  A: 

If you use this in more than one location frequently you could also consider writing your own custom selector (http://answers.oreilly.com/topic/1055-creating-a-custom-filter-selector-with-jquery/)

jQuery.expr[':'].greenbg = function(elem) {
        return jQuery(elem).css('background-color') === 'green';
};

Then you would simply do $('div:visible:greenbg').stuffs()

Jake Wharton
As @SLaks pointed out this won't match `#0f0` but provides a single place for you to include all those checks.
Jake Wharton
A: 

Hi,

$.expr[":"].green = function(a) { 
    return /^green$/.test($(a).css('backgroundColor')); 
}; 

should do it.

Kind Regards

--Andy

jAndy
Why are you using a regex?
SLaks
Good question, I saw it once on a paper from Paul Irish. I'm not exactly sure if it's faster or has another benefits. Just used to it.
jAndy
If you happen to be using many instances of named colors in CSS then I suppose this would match them all as being flavors of green. http://www.w3schools.com/css/css_colorsfull.asp
Jake Wharton