1

I want to set CSS properties by a variable: e.g. {background: red; }

My code has a mistake, it does not work: js fiddle

js

            var Key = 'background';
            var Value = 'yellow';


                $('.test').css({

                    Key: Value
                });
1
  • 1
    this kind of syntax may require the exact string like as CSS code you type (which does not support any kind of variable), so use other kind of syntax provided by the answers below Commented Mar 31, 2014 at 11:13

4 Answers 4

3

It should be like .css("propertyname","value"). So your code will need to change like

$('.test').css(Key, Value);

See this for more reference

Sign up to request clarification or add additional context in comments.

Comments

3

use:

$('.test').css(Key, Value);

Working Example

Comments

2

See there are two ways of applying css to an element with jQuery:

First:

$(selector).css("propertyname","value");

Second:

$(selector).css({"propertyname":"value"}); // object with key : value pair

What is the issue in your code?

The issue is

{Key:Value}

object key which has to be a string ("") so that does not work in your case your best bet to go with first one:

$('.test').css(Key, Value);

to understand this go to this Fiddle

Comments

1

If you want to use the plain object css overload, then you will need to do it like this:

$('.test').css({
'background': Value
});

Or

var properties ={};
var Key = 'background';
var Value = 'yellow';

properties[Key] = Value;

$('.test').css(properties);

The problem with {Key: Value} is that it thinks the property name is Key and not background.

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.