9

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?

2
  • 3
    Do your logic with classes and the styling in CSS. Then you can check if the class exists with hasClass. Commented Aug 24, 2013 at 0:25
  • that's one way. thanks :) Commented Aug 24, 2013 at 0:29

2 Answers 2

7

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 == '' ) {
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

Whilst this is good, but it only checks for in-line styling I think?
You're right, which is yet another reason why you shouldn't really do this when you have other options. stackoverflow.com/a/2239605/1351133 is a better/more thorough solution to this than what I posted.
Good link there, very relevant to the OP's requirements =) (Even if the class route is undoubtedly the best method!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.