Is it possible to do an if statement in javascript/jquery to determine:
If the value of a certain element’s css attribute is equal to a given value?
such as:
if( $('.box').css(background-color = blue) ){
// do this...
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
cssJQuery method, when given only one parameter, will return the value for the given paramenter. You can try this:The above sample will only work for the first element in the JQuery selector, therefore you should use the
.eachJQuery method to iterate through the whole selector if you have more than one element in it.Please note that the
.cssJQuery method returns a RGB combination in most browsers (except IE), so testing it against a string such asbluewill not suffice for non-IE browsers. You can test that in the JQuery API site and my fiddle.And here’s with the proper
.eachiteration:JSFiddle
Edit: over a year and half later, I feel like this answer deserves an update.
For most use cases, I’d recommend using a CSS class:
This allows the usage of the
addClass(),removeClass(),toggleClass()methods for manipulation, as well ashasClass()for checking:This works seamlessly in all browsers without needing hacks, and as a plus you get better separation of concerns — that is, if your styling ever changes, say
.blue { color: lightblue; }, the JS will keep working without modifications.Note: of course, this approach is not suitable for a couple rare use cases where the color value is dynamically generated (e.g. using
Math.random()or picking a color value off a canvas pixel), in these rare use cases you can still use the first solution in this answer.