0

I create an array from splitting a string which have the css properties and then I pass the array to the css method but it doesn't work.

var cssString = "'top':'25px', 'height':'400px'";
var cssArray = new Array;
cssArray = cssString.split(",");
$("#div").css(cssArray);
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

You can convert your string in JSON object then pass it .css() method.

var cssString = "'top':'25px', 'height':'400px'".replace(/'/g, '\"'); // replace single quotes
var jsonStrring = "{" + cssString + "}"; //Create a string in JSON format
var jsonObject = JSON.parse(jsonStrring); //Convert to JSON object
$("#div").css(jsonObject); //Pass JSON object
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • I was thinking in that direction too, but it's not valid JSON syntax. "SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data" – Guffa Jul 06 '14 at 16:21
  • @Guffa, Thanks for pointing out fixed problem (with single quotes) http://jsfiddle.net/7trvW/ – Satpal Jul 06 '14 at 16:27
  • 1
    Wow thanks for the answer, it works perfectly! I thought that the css method was working with normal arrays. One last question: Why is it necessary replace the single quotes? I need to read more about json. – user2409347 Jul 06 '14 at 16:43
  • @user2409347, Read [jQuery single quote in JSON response](http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response) Proper reason is provide. To sum up "single quotes is not allowed." – Satpal Jul 06 '14 at 17:02
0

If your string was valid JSON, you could parse it into an object and call $("#div").css(cssJsonObject);.

Since it's not valid JSON (no curly brackets, and the wrong quotes), you'll need to either make sure your string is valid JSON and parse it accordingly, or start with a valid javascript object in the first place, like:

var cssObject = {top:"25px", height:"400px"};
$("#div").css(cssObject);
Joe Enos
  • 39,478
  • 11
  • 80
  • 136