Motion
Motion

Reputation: 116

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);}";
    document.body.appendChild(sheet);

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

Upvotes: 0

Views: 352

Answers (3)

Veetase
Veetase

Reputation: 154

You can just write a css class in css file, and then apply the css class on runtime by javascript, like this:

html file:
<div id="test"></div>

css file:
.context-menu-icon-case1: {
  color: xxx,
  width: xxx
}

javascript file:
var ele = document.getElementById("test");
ele.className += "context-menu-icon-case1";

Upvotes: -1

guest271314
guest271314

Reputation: 1

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.

<head>
  <script>
    var cssupdate = `.context-menu-icon-case1:before {
                       content: url(progressbar.png);
                    }`;
    var cssfile = "style.css";
    fetch(cssfile)
    .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); 
      document.querySelector("head").appendChild(link);
    });
  </script>
</head>

plnkr http://plnkr.co/edit/Gh0qR4CcQPROXCldX9OC?p=preview

Upvotes: 2

user5116395
user5116395

Reputation:

You can't. I am sorry. Good news is you don't need to. Inserting CSS through Javascript is the same as reading from a css file.

Upvotes: 2

Related Questions