3

How can I store property name as a variable?

Example code:

var propertyName = 'margin-top';
$('elem').css({ propertyName : '10px' });
1
  • .css(strWhatever, value); or make a dynamic object using array syntax. Commented Jan 15, 2015 at 21:12

2 Answers 2

2

You can store the argument for css() as a variable, and then add the property to it:

var propertyName = 'margin-top';
var cssArg = {};
cssArg[propertyName] = '10px';
$('elem').css(cssArg);

Edit:

In the future (ES6) you'll be able to do that in one line using computed properies:

$('elem').css({ [propertyName] : '10px'});

But for now, you have to stick with the long way.

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

Comments

0

For single CSS directive change, you could simply do this:

var propertyName = 'margin-top';
$('elem').css(propertyName, '10px');

If you still need to pass Object in order to manipulate multiple directives, you could try this:

var cssData = {};
var propertyName = 'margin-top';
cssData[propertyName] = '10px';

$('elem').css(cssData);

See Documentation

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.