Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if .css property was set

My code looks like this

if($(element).css("background-color") == null){
  $(element).css("background-color", "white");
}

I want to make sure that if the color wasn't set in the style.css file, I add it. But that code is not working. It's always returning rgba(0,0,0,0). The browser I am working with is Chrome.

Is there another way to check if the color wasn't set?

like image 291
TatiOverflow Avatar asked Aug 24 '13 00:08

TatiOverflow


2 Answers

CSS:

.background-set { background-color: white; }

jQuery:

var $el = $(element);

if( !$el.hasClass('background-set') ){
   $el.addClass('background-set');
}

Though I'm not sure why you'd need to check. You can just add it without the condition.


Alternatively:

if ( $el.prop('style').backgroundColor == '' ) {
   ... 
}

or

if ( $el.get(0).style.backgroundColor == '' ) {
   ...
}
like image 133
vol7ron Avatar answered Sep 23 '22 22:09

vol7ron


The method suggested by elclanrs is the most elegant way of handling this and should be the preferred method. However, for the sake of sating curiosity, you could achieve the same result using a jQuery Attribute Contains Selector.

$("div[style*='background-color']").text("I have a background color!");

jsFiddle demo

like image 27
oddurad Avatar answered Sep 24 '22 22:09

oddurad