1

Im trying to convert normal css markup into an object:

.btn {
  border-radius: 28px;
  padding: 10px 20px 10px 20px;
  border:1px solid #000;
}

so it becomes

var btn = {
  "border-radius": "28px",
  "padding": "10px 20px 10px 20px",
  "border":"1px solid #000",
};

then I can use it with jquery css function to style other elements

$(".el").css(btn);

I have tried using both JSON.parse(), and JSON.stringify(), but no success.

3
  • can u reproduce the problem in stacksnippet? Commented Feb 10, 2018 at 5:23
  • JSON.stringify will not work because it's a string and not am object. Commented Feb 10, 2018 at 5:24
  • normal css markup ? Your first variable not an normal css, It's an invalid string. Commented Feb 10, 2018 at 5:42

2 Answers 2

2

Why dont you simply do:

$(".el").addClass("btn");

Still if you want to proceed with the approach you suggested, then you can do something like this:

var btn = `{
  border-radius: 28px;
  padding: 10px 20px 10px 20px;
  border:1px solid #000;
}`;

formattedBtn = btn.split("\n");
/* Remove first element and last element as they are 
{ and } */
formattedBtn.pop();
formattedBtn.shift();

var obj = {};
formattedBtn.forEach(
  (el) => {
    let proerty = el.split(":");
    obj[proerty[0].trim()] = proerty[1].trim().replace(/;/g, "");
  }
)

console.log(obj);

$(function(){
  $("#but").css(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="but">My Button</button>

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

2 Comments

Try with $(".el").css(btn); of course it's not working.
@Pedram yea forgot to remove the ;. Fixed now, check the updated snippet.
0

    var btn = '{border-radius: 28px;padding: 10px 20px 10px 20px;border:1px solid #000}';
    btn = btn.replace(/[{}]/gi, " ").trim(); // remove '{' and '}'

    var my_result = [], temp;
    $.each(btn.split(";"), function(i, css_prop){
        temp = css_prop.split(":");
        my_result[temp[0]] = temp[1];
    });

    console.log('my_result',my_result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.