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.
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>
.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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With