0

In JavaScript using jQuery, how does one test whether the color assigned to an element is red blue, having an id as 'ID'.

The JavaScript statement used to set the color for the element is:

$('#ID').css({'background-color':'#FF0000'});
1
  • If you've just set the colour then you know what it is, I'm unsure as to why you would want to query this. The page should be dumb and certainly the DOM should not be used to store state through property values. You could add a dummy class, such as "colourBlue" or "colourRed" to your element and then use the existence of that to get the current colour but I still maintain it's not the place to save state. Commented Dec 23, 2010 at 9:19

2 Answers 2

3

You should be able to check this with the css function with only one argument:

if ($('#ID').css('background-color') == '#FF0000') {
    // your code
}

My preference would be to add a class (red or blue) and check using hasClass:

if ($('#ID').hasClass('red')) {
    // your code
}
Sign up to request clarification or add additional context in comments.

Comments

0

I also would suggest using classes, but if you really want to know the color of something I would use a javascript library to parse the return from .css, like this one: http://www.phpied.com/rgb-color-parser-in-javascript/

Here is an example of it in use: http://jsfiddle.net/keegan3d/5SBpk/

Comments

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.