1

I have a javascript variable with the following value:

var style ="border-left:12px solid;border-color:red;position:relative;"

How can I apply it to a div like below:

<div class='my-div'></div>

I tried:

$('.my-div').css({style});

but failed spectacularly :(

6
  • 2
    Because that is not how you make an object Commented Nov 3, 2015 at 18:18
  • stackoverflow.com/questions/14829948/… Commented Nov 3, 2015 at 18:18
  • Read the docs, it's clearly explained how to make the object required. Or go simple and use a class. Commented Nov 3, 2015 at 18:19
  • api.jquery.com/css Commented Nov 3, 2015 at 18:20
  • 1
    @RayonDabre: Thank you Rayon, your solution worked... Commented Nov 4, 2015 at 5:33

1 Answer 1

1
var style = {
    borderLeft:'12px solid',
    borderColor:'red',
    position:'relative'
}

The object should look like this. The CSS method takes in an object param. Doing a style string concat will work, but it's ugly.

Or use a class and be simple.

$('.my-div').css(style); //append style object to jQuery object

Note that using this object notation can also be beneficial because the properties can have logic in them, say for animations, or changing value dependencies.

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

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.