Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
StorySystems Avatar asked Mar 28 '26 21:03

StorySystems


2 Answers

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>
like image 96
Rajaprabhu Aravindasamy Avatar answered Apr 02 '26 03:04

Rajaprabhu Aravindasamy


.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/

like image 35
Markai Avatar answered Apr 02 '26 02:04

Markai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!