StorySystems
StorySystems

Reputation: 165

JQuery apply css stored in variable

I have a div which is to be styled using CSS styles stored in a variable. Like so:

var styles = 'font-weight","bold"';

$('div').css(styles);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>The Div to be styled</div>

This demonstrates what I want to do, but it won't work. Does anyone have any ideas. Thanks.

Upvotes: 2

Views: 240

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

var styles = {'font-weight':'bold'};
$('div').css(styles);

In your code you are passing a single string argument to the .css() function. And that is not a supported valid signature with .css() for setting up a style value.

var styles = {'font-weight':'bold'};
$('div').css(styles);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>The Div to be styled</div>

Upvotes: 9

Markai
Markai

Reputation: 2098

.css requests either a pair of two strings (rulename and value) or an object with name/value pairs if you try to set a rule. If you only hand one string, it tries to return the value of the rule with matching name (which in your case does not exist).

Try this:

var styles = {'font-weight': "bold"};

$('div').css(styles);

working fiddle: http://jsfiddle.net/ocgb77m8/

Upvotes: 1

Related Questions