Alko
Alko

Reputation: 1439

jQuery, convert css classes into an object

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.

Upvotes: 1

Views: 45

Answers (2)

Marco Sanchez
Marco Sanchez

Reputation: 788

    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>

Upvotes: 0

void
void

Reputation: 36703

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>

Upvotes: 2

Related Questions