2

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.

3
  • .css({fontWeight: 'bold'})? Commented Nov 4, 2014 at 13:15
  • 2
    Why not use a class and set style using any CSS rule? This is how it should be done imho Commented Nov 4, 2014 at 13:17
  • Related: jquery css() is not working with a string Commented Nov 4, 2014 at 13:19

2 Answers 2

9

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>

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.