Motion Motion - 1 year ago 82
CSS Question

How to create class in a custom CSS file by JavaScript?

I want to create a CSS class at runtime using JavaScript and write in a custom CSS file.

Now I wrote the code (see below) and created my class but I don't know how to create it in my CSS file.

var sheet = document.createElement('style')
sheet.innerHTML = ".context-menu-icon-case1:before{content: url(progressbar.png);}";

It creates the CSS class in my current page but I want to create it in a custom css file.

Answer Source

You can request the existing .css file using XMLHttpRequest() or fetch() instead of loading the file at html, append the new style rule to the .css file at XMLHttpRequest.responseText or response.text(), or using FileReader.

Create a Blob or File object, or encoded text representation of new css text appended to existing file, create a <link> element with rel attribute set to stylesheet, href attribute to an objectURL, data URI or encoded text of the created file, append the link element to document.head.

    var cssupdate = `.context-menu-icon-case1:before {
                       content: url(progressbar.png);
    var cssfile = "style.css";
    .then(response => response.text())
    .then(currentcss => {
      var css = currentcss + "\n" + `${cssupdate}`;
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.type = "text/css";
      link.href = "data:text/css," + encodeURIComponent(css); 


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download