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?
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 == '' ) {
...
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With