CSS Styling from JSON

17,663

This should do it:

var styles = {
  "#textContainer": {
    "border": "blue solid 2px;",
    "background-color": "#ff0;"
  },
  "#textContainer > button": {
    "color": "#f00"
  }
};


var newStyle = document.createElement('style');
newStyle.type = "text/css";
newStyle.appendChild(document.createTextNode(getCSS()));

document.querySelector("#textContainer").appendChild(newStyle);

function getCSS() {
  var css = [];
  for (let selector in styles) {
    let style = selector + " {";
    
    for (let prop in styles[selector]) {
      style += prop + ":" + styles[selector][prop];
    }
    
    style += "}";
    
    css.push(style);
  }
  
  return css.join("\n");
}
<div id="textContainer" class="col-xs-offset-8 col-xs-4">
  <button type="button" class="btn btn-default btn-lg">Hello</button>
</div>

Share:
17,663
Zze
Author by

Zze

Passionate about front-end web development on a .NET stack.

Updated on June 06, 2022

Comments

  • Zze
    Zze almost 2 years

    I am creating an app in which you can apply custom css to html templates. The custom css is drawn from a .json file, I then parse it, transmute it into css and then intstantiate a custom <style>.

    I think I am very close to having this working as intended, the only issue is that I can't quite work out how to remove the , in between a selectors properties. i.e. in the example below... #textContainer {border:blue solid 2px;,background-color:#ff0;} the comma right before background-color.

    note: in the example below, the styles object represents the external .json file.

    var styles = {
      "#textContainer": {
        "border": "blue solid 2px;",
        "background-color": "#ff0;"
      },
      "#textContainer > button": {
        "color": "#f00"
      }
    };
    
    
    var newStyle = document.createElement('style');
    newStyle.type = "text/css";
    
    newStyle.appendChild(document.createTextNode(getCSS()));
    document.querySelector("#textContainer").appendChild(newStyle);
    
    function getCSS() {
      var css = [];
      for (let selector in styles) {
        console.log(">> Selector >> ", selector, JSON.stringify(styles[selector]));
        var nest = [];
        for (let prop in styles[selector]) {
          nest.push(prop + ":" + JSON.stringify(styles[selector][prop]));
        }
        css.push(selector + " " + JSON.stringify(styles[selector]));
      }
    
      var cssStr = css.join("\n");
      cssStr = cssStr.replace(/["]/g, "");
      console.log("-------------------------------------------------");
      console.log(cssStr);
      return cssStr;
    }
    <div id="textContainer" class="col-xs-offset-8 col-xs-4">
      <button type="button" class="btn btn-default btn-lg">Hello</button>
    </div>