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);

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

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, Thanks for pointing out fixed problem (with single quotes) jsfiddle.net/7trvW
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, Read jQuery single quote in JSON response Proper reason is provide. To sum up "single quotes is not allowed."
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);

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.