386

I need to create a CSS stylesheet class dynamically in JavaScript and assign it to some HTML elements like - div, table, span, tr, etc and to some controls like asp:Textbox, Dropdownlist and datalist.

Is it possible?

It would be nice with a sample.

Vishwanath
  • 6,284
  • 4
  • 38
  • 57
Himadri
  • 8,600
  • 15
  • 47
  • 70
  • 2
    take a look at https://github.com/Box9/jss – jedierikb Sep 07 '12 at 14:49
  • See also http://stackoverflow.com/questions/1212500/jquery-create-css-rule-class-runtime – jantimon Sep 07 '12 at 15:39
  • Notice in some cases what you really want might not be exactly creating a css class and applying it, but you've come here because you want to add multiple styles at once maybe because it's "faster"(easier to type). In that case, check the answers on this question, some of them are very useful: https://stackoverflow.com/questions/3968593/how-can-i-set-multiple-css-styles-in-javascript – aderchox Jun 29 '21 at 03:30

17 Answers17

509

Here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #f00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';
<div id="someElementId">test text</div>
Nexo
  • 2,125
  • 2
  • 10
  • 20
I.devries
  • 8,747
  • 1
  • 27
  • 29
  • 11
    My use case is a bookmarklet that is highlighting certain elements for QA purposes. – TomG Apr 29 '11 at 19:14
  • My own use case is I am writing a deeply configurable jQuery widget and need to be able to apply customized classes that the user specifies and I build at loadtime. – jaydel May 30 '11 at 15:00
  • 25
    Pretty sure this results in a unknown runtime error in IE 8 and less. – Andy Hume Oct 31 '11 at 10:52
  • My use case is for creating classes at runtime with objects name provided by user of the class, and then use it automatically without asking user to create one... – Vishwanath Dec 25 '11 at 03:53
  • 1
    My use case is loading a random Google web font and then giving the randomFont class the font-family :-) – w00t Feb 15 '12 at 12:11
  • 33
    Another use case would be where you want a single JS lib without dependencies on CSS files. In my case I want lightweight growl-style alert popups out-of-the-box. – xeolabs Aug 12 '13 at 07:24
  • 2
    I'm doing something similar like w00t. I'm working on a interactive html5 app, which will have writing on a canvas, and I want to let my user to select from a wide range of fonts to use. Rather than having a loooong css with all the font, I'm planning on creating a backend where I'll just upload the font data and whenever the program is loaded, a little call to a webservice brings the font and adds them – CJLopez Mar 16 '15 at 20:02
  • how to achieve this in IE8? – Akbar Basha May 07 '15 at 11:09
  • I need to hack in a by-pass solution on a projo. Someone else already fubared the existing Bootstrap. I don't want to push changes to /every/ file in the source. There's always a reason to do something stupid that's never in doubt. – Gus Crawford Jun 19 '15 at 06:41
  • 5
    I once needed to highlight and unhighlight many elements in a page at once, corresponding to a user's selection. Applying and removing the classes to all the elements was slooooow. So instead, in the browser after my ajax request returned data, I created one css class per possible selection and applied it to each element, defining the rule for all classes with no attributes. Once a selection was made, rewriting the rule itself resulted in amazing **lightning speed** updating all the elements on the page. So yeah, there's a use case. – ErikE Mar 21 '16 at 23:49
  • My use case is generating classes based on some data stored as JSON format – Parth Apr 07 '16 at 09:38
  • My use case is to generate a "hot schema" (red to green) classes by percentages. From this: [http://stackoverflow.com/a/7128796/3786841](http://stackoverflow.com/a/7128796/3786841) So I can use them like, `` – Jeancarlo Fontalvo Mar 06 '17 at 13:04
  • 1
    You're a lifesaver! Use case: needed a way to create parameterized custom animations on the fly. – Junkey McKrat May 22 '18 at 18:13
  • im doing exactly what Junkey is doing. im considering creating a class with JS because i want to keep styling separate from JS, but the values i need to set are dynamic and can only be obtained from JS. otherwise ill have to be constantly styling crap in JS – oldboy Jan 26 '20 at 04:51
  • For aspect ratio boxes I came across [this](https://css-tricks.com/aspect-ratio-boxes/#article-header-id-7), where CSS custom properties are used. Before that I would generate the CSS with JS like in this answer. Just saying, with custom properties you can pass values from the HTML to the CSS and work with that, so avoiding style creations with JS. – lowtechsun Feb 04 '20 at 18:17
  • Another use case: using the power of a full programming language (in my case TypeScript transpiled to JavaScript) to generate CSS with features such as inheritance, without having to take a dependency on CSS preprocessors like LESS/SASS. – Eric Mutta Oct 31 '21 at 23:02
  • I wonder why everybody tells his/her use case?.. Anyway, `style.type` seems to be optional. – x-yuri Sep 26 '22 at 22:46
  • 2
    I know this is an old post, but to update it, `document.getElementsByTagName('head')[0].appendChild(style);` should be `document.head.appendChild(style)`. – Scott Marcus Nov 04 '22 at 17:23
129

Found a better solution, which works across all browsers.
Uses document.styleSheet to add or replace rules. Accepted answer is short and handy but this works across IE8 and less too.

function createCSSSelector (selector, style) {
  if (!document.styleSheets) return;
  if (document.getElementsByTagName('head').length == 0) return;

  var styleSheet,mediaType;

  if (document.styleSheets.length > 0) {
    for (var i = 0, l = document.styleSheets.length; i < l; i++) {
      if (document.styleSheets[i].disabled) 
        continue;
      var media = document.styleSheets[i].media;
      mediaType = typeof media;

      if (mediaType === 'string') {
        if (media === '' || (media.indexOf('screen') !== -1)) {
          styleSheet = document.styleSheets[i];
        }
      }
      else if (mediaType=='object') {
        if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) {
          styleSheet = document.styleSheets[i];
        }
      }

      if (typeof styleSheet !== 'undefined') 
        break;
    }
  }

  if (typeof styleSheet === 'undefined') {
    var styleSheetElement = document.createElement('style');
    styleSheetElement.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(styleSheetElement);

    for (i = 0; i < document.styleSheets.length; i++) {
      if (document.styleSheets[i].disabled) {
        continue;
      }
      styleSheet = document.styleSheets[i];
    }

    mediaType = typeof styleSheet.media;
  }

  if (mediaType === 'string') {
    for (var i = 0, l = styleSheet.rules.length; i < l; i++) {
      if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) {
        styleSheet.rules[i].style.cssText = style;
        return;
      }
    }
    styleSheet.addRule(selector,style);
  }
  else if (mediaType === 'object') {
    var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0;
    for (var i = 0; i < styleSheetLength; i++) {
      if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
        styleSheet.cssRules[i].style.cssText = style;
        return;
      }
    }
    styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength);
  }
}

Function is used as follows.

createCSSSelector('.mycssclass', 'display:none');
Yves M.
  • 29,855
  • 23
  • 108
  • 144
Vishwanath
  • 6,284
  • 4
  • 38
  • 57
  • 2
    Confirmed working with IE8. I did have to add a "styleSheet.cssRules[i].selectorText &&" and "styleSheet.rules[i].selectorText &&"in the mediaType for-loop ifs because it didn't work in Chrome, apparently sometimes the selectorText isn't defined. – w00t Feb 15 '12 at 12:26
  • @w00t Could you please paste or edit the code to make it work? – Hengjie May 17 '13 at 16:01
  • I just opened the Chrome (Version 34.0.1847.132) pasted the functions and executed it, but it didn't work: "TypeError: Cannot read property 'length' of null". Can it be that does not work creating it from developer console? – dnuske May 04 '14 at 02:09
  • It turns out some versions of chrome (or chromium) don't allow to insertRule on index 0. Here is the fix: styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length); – dnuske May 05 '14 at 19:17
  • 2
    @dnuske I encountered the same issue. it turns out that styleSheet.cssRules evaluates to null. the fix I've used is to create a new variable `var styleSheetLength = styleSheet.cssRules ? styleSheet.cssRules.length : 0` and substitute its usage over the implementation of the function. – Raj Nathani Jul 05 '14 at 03:41
  • @Vishwanath I am now getting a security error in Firefox when using this function. Can you confirm? – Matt Baker Sep 21 '14 at 00:24
  • @Vishwanath yes, this error is triggered in Firefox: http://stackoverflow.com/questions/21642277/security-error-the-operation-is-insecure-in-firefox-document-stylesheets – Matt Baker Sep 21 '14 at 00:43
  • This solution performs well cross-platform, and does not add unnesicary rules when modifying existing selectors. – Stephanie Jun 09 '15 at 04:01
  • This solution gives an exception in chrome >64 "Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules" – CaptainHere Oct 22 '18 at 01:46
  • just pasted into console in chrome: VM261:55 Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at createCSSSelector (:55:40) at :1:1 – B''H Bi'ezras -- Boruch Hashem Feb 11 '19 at 01:19
  • what if theres no current stylesheet on the document – B''H Bi'ezras -- Boruch Hashem Feb 11 '19 at 01:57
  • I refactored your code, added a removeRule function and it now uses the same stylesheet every time. https://jsfiddle.net/n1pujm7x/ – shano12 Jun 17 '21 at 10:30
33

Short answer, this is compatible "on all browsers" (specifically, IE8/7):

function createClass(name,rules){
    var style = document.createElement('style');
    style.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(style);
    if(!(style.sheet||{}).insertRule) 
        (style.styleSheet || style.sheet).addRule(name, rules);
    else
        style.sheet.insertRule(name+"{"+rules+"}",0);
}
createClass('.whatever',"background-color: green;");

And this final bit applies the class to an element:

function applyClass(name,element,doRemove){
    if(typeof element.valueOf() == "string"){
        element = document.getElementById(element);
    }
    if(!element) return;
    if(doRemove){
        element.className = element.className.replace(new RegExp("\\b" + name + "\\b","g"));
    }else{      
        element.className = element.className + " " + name;
    }
}

Here's a little test page as well: https://gist.github.com/shadybones/9816763

The key little bit is the fact that style elements have a "styleSheet"/"sheet" property which you can use to to add/remove rules on.

Snowburnt
  • 6,523
  • 7
  • 30
  • 43
shadybones
  • 360
  • 4
  • 6
18

There is a light jQuery plugin which allows to generate CSS declarations: jQuery-injectCSS

In fact, it uses JSS (CSS described by JSON), but it's quite easy to handle in order to generate dynamic css stylesheets.

$.injectCSS({
    "#test": {
        height: 123
    }
});
Yako
  • 3,405
  • 9
  • 41
  • 71
  • similar to https://stackoverflow.com/questions/1212500/create-a-css-rule-class-with-jquery-at-runtime/1214217#1214217 . – user1742529 Sep 16 '19 at 08:06
7

YUI has by far the best stylesheet utility I have seen out there. I encourage you to check it out, but here's a taste:

// style element or locally sourced link element
var sheet = YAHOO.util.StyleSheet(YAHOO.util.Selector.query('style',null,true));

sheet = YAHOO.util.StyleSheet(YAHOO.util.Dom.get('local'));


// OR the id of a style element or locally sourced link element
sheet = YAHOO.util.StyleSheet('local');


// OR string of css text
var css = ".moduleX .alert { background: #fcc; font-weight: bold; } " +
          ".moduleX .warn  { background: #eec; } " +
          ".hide_messages .moduleX .alert, " +
          ".hide_messages .moduleX .warn { display: none; }";

sheet = new YAHOO.util.StyleSheet(css);

There are obviously other much simpler ways of changing styles on the fly such as those suggested here. If they make sense for your problem, they might be best, but there are definitely reasons why modifying CSS is a better solution. The most obvious case is when you need to modify a large number of elements. The other major case is if you need your style changes to involve the cascade. Using the DOM to modify an element will always have a higher priority. It's the sledgehammer approach and is equivalent to using the style attribute directly on the HTML element. That is not always the desired effect.

tagurit
  • 494
  • 5
  • 13
Russell Leggett
  • 8,795
  • 3
  • 31
  • 45
6

Here is Vishwanath's solution slightly rewritten with comments :

function setStyle(cssRules, aSelector, aStyle){
    for(var i = 0; i < cssRules.length; i++) {
        if(cssRules[i].selectorText && cssRules[i].selectorText.toLowerCase() == aSelector.toLowerCase()) {
            cssRules[i].style.cssText = aStyle;
            return true;
        }
    }
    return false;
}

function createCSSSelector(selector, style) {
    var doc = document;
    var allSS = doc.styleSheets;
    if(!allSS) return;

    var headElts = doc.getElementsByTagName("head");
    if(!headElts.length) return;

    var styleSheet, media, iSS = allSS.length; // scope is global in a function
    /* 1. search for media == "screen" */
    while(iSS){ --iSS;
        if(allSS[iSS].disabled) continue; /* dont take into account the disabled stylesheets */
        media = allSS[iSS].media;
        if(typeof media == "object")
            media = media.mediaText;
        if(media == "" || media=='all' || media.indexOf("screen") != -1){
            styleSheet = allSS[iSS];
            iSS = -1;   // indication that media=="screen" was found (if not, then iSS==0)
            break;
        }
    }

    /* 2. if not found, create one */
    if(iSS != -1) {
        var styleSheetElement = doc.createElement("style");
        styleSheetElement.type = "text/css";
        headElts[0].appendChild(styleSheetElement);
        styleSheet = doc.styleSheets[allSS.length]; /* take the new stylesheet to add the selector and the style */
    }

    /* 3. add the selector and style */
    switch (typeof styleSheet.media) {
    case "string":
        if(!setStyle(styleSheet.rules, selector, style));
            styleSheet.addRule(selector, style);
        break;
    case "object":
        if(!setStyle(styleSheet.cssRules, selector, style));
            styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length);
        break;
    }
user3705905
  • 86
  • 1
  • 3
6

One liner, attach one or many new cascading rule(s) to the document.

This example attach a cursor:pointer to every button, input, select.

document.body.appendChild(Object.assign(document.createElement("style"), {textContent: "select, button, input {cursor:pointer}"}))
Qwerty
  • 29,062
  • 22
  • 108
  • 136
NVRM
  • 11,480
  • 1
  • 88
  • 87
5

https://jsfiddle.net/xk6Ut/256/

One option to dynamically create and update CSS class in JavaScript:

  • Using Style Element to create a CSS section
  • Using an ID for the style element so that we can update the CSS
    class

.....

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) 
             document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

...

    var cssText = '.testDIV{ height:' + height + 'px !important; }';
    writeStyles('styles_js', cssText)
Razan Paul
  • 13,618
  • 3
  • 69
  • 61
5

As of IE 9. You can now load a text file and set a style.innerHTML property. So essentially you can now load a css file through ajax (and get the callback) and then just set the text inside of a style tag like this.

This works in other browsers, not sure how far back. But as long as you don't need to support IE8 then it would work.

// RESULT: doesn't work in IE8 and below. Works in IE9 and other browsers.
$(document).ready(function() {
    // we want to load the css as a text file and append it with a style.
    $.ajax({
        url:'myCss.css',
        success: function(result) {
            var s = document.createElement('style');
            s.setAttribute('type', 'text/css');
            s.innerHTML = result;
            document.getElementsByTagName("head")[0].appendChild(s);
        },
        fail: function() {
            alert('fail');
        }
    })
});

and then you can have it pull an external file like the myCss.css

.myClass { background:#F00; }
Codeguy
  • 51
  • 1
  • 1
4

Using google closure:

you can just use the ccsom module:

goog.require('goog.cssom');
var css_node = goog.cssom.addCssText('.cssClass { color: #F00; }');

The javascript code attempts to be cross browser when putting the css node into the document head.

Joe Heyming
  • 777
  • 6
  • 11
4

An interesting project which could help you out in your task is JSS.

JSS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free and reusable way. It can compile in the browser, server-side or at build time in Node.

JSS library allows you to inject in the DOM/head section using the .attach() function.

Repl online version for evaluation.

Further information on JSS.

An example:

// Use plugins.
jss.use(camelCase())

// Create your style.
const style = {
  myButton: {
    color: 'green'
  }
}

// Compile styles, apply plugins.
const sheet = jss.createStyleSheet(style)

// If you want to render on the client, insert it into DOM.
sheet.attach()
tagurit
  • 494
  • 5
  • 13
GibboK
  • 71,848
  • 143
  • 435
  • 658
3

I was looking through some of the answers here, and I couldn't find anything that automatically adds a new stylesheet if there are none, and if not simply modifies an existing one that already contains the style needed, so I made a new function (should work accross all browsers, though not tested, uses addRule and besides that only basic native JavaScript, let me know if it works):

function myCSS(data) {
    var head = document.head || document.getElementsByTagName("head")[0];
    if(head) {
        if(data && data.constructor == Object) {
            for(var k in data) {
                var selector = k;
                var rules = data[k];

                var allSheets = document.styleSheets;
                var cur = null;

                var indexOfPossibleRule = null,
                    indexOfSheet = null;
                for(var i = 0; i < allSheets.length; i++) {
                    indexOfPossibleRule = findIndexOfObjPropInArray("selectorText",selector,allSheets[i].cssRules);
                    if(indexOfPossibleRule != null) {
                        indexOfSheet = i;
                        break;
                    }
                }

                var ruleToEdit = null;
                if(indexOfSheet != null) {

                    ruleToEdit = allSheets[indexOfSheet].cssRules[indexOfPossibleRule];

                } else {
                    cur = document.createElement("style");
                    cur.type =  "text/css";
                    head.appendChild(cur);
                    cur.sheet.addRule(selector,"");
                    ruleToEdit = cur.sheet.cssRules[0];
                    console.log("NOPE, but here's a new one:", cur);
                }
                applyCustomCSSruleListToExistingCSSruleList(rules, ruleToEdit, (err) => {
                    if(err) {
                        console.log(err);
                    } else {
                        console.log("successfully added ", rules, " to ", ruleToEdit);
                    }
                });
            }
        } else {
            console.log("provide one paramter as an object containing the cssStyles, like: {\"#myID\":{position:\"absolute\"}, \".myClass\":{background:\"red\"}}, etc...");
        }
    } else {
        console.log("run this after the page loads");
    }

};  

then just add these 2 helper functions either inside the above function, or anywhere else:

function applyCustomCSSruleListToExistingCSSruleList(customRuleList, existingRuleList, cb) {
    var err = null;
    console.log("trying to apply ", customRuleList, " to ", existingRuleList);
    if(customRuleList && customRuleList.constructor == Object && existingRuleList && existingRuleList.constructor == CSSStyleRule) {
        for(var k in customRuleList) {
            existingRuleList["style"][k] = customRuleList[k];
        }

    } else {
        err = ("provide first argument as an object containing the selectors for the keys, and the second argument is the CSSRuleList to modify");
    }
    if(cb) {
        cb(err);
    }
}

function findIndexOfObjPropInArray(objPropKey, objPropValue, arr) {
    var index = null;
    for(var i = 0; i < arr.length; i++) {
        if(arr[i][objPropKey] == objPropValue) {
            index = i;
            break;
        }
    }
    return index;
}

(notice that in both of them I use a for loop instead of .filter, since the CSS style / rule list classes only have a length property, and no .filter method.)

Then to call it:

myCSS({
    "#coby": {
        position:"absolute",
        color:"blue"
    },
    ".myError": {
        padding:"4px",
        background:"salmon"
    }
})

Let me know if it works for your browser or gives an error.

  • For some reason adding `!important` makes the declaration empty. Any idea how to use "important"? – Sych Nov 01 '20 at 16:38
2

Here is my modular solution:

var final_style = document.createElement('style');
final_style.type = 'text/css';

function addNewStyle(selector, style){
  final_style.innerHTML += selector + '{ ' + style + ' } \n';
};

function submitNewStyle(){
  document.getElementsByTagName('head')[0].appendChild(final_style);

  final_style = document.createElement('style');
  final_style.type = 'text/css';
};

function submitNewStyleWithMedia(mediaSelector){
  final_style.innerHTML = '@media(' + mediaSelector + '){\n' + final_style.innerHTML + '\n};';
    submitNewStyle();
};

You basically anywhere in your code do:
addNewStyle('body', 'color: ' + color1); , where color1 is defined variable.

When you want to "post" the current CSS file you simply do submitNewStyle(),
and then you can still add more CSS later.

If you want to add it with "media queries", you have the option.
After "addingNewStyles" you simply use submitNewStyleWithMedia('min-width: 1280px');.


It was pretty useful for my use-case, as I was changing CSS of public (not mine) website according to current time. I submit one CSS file before using "active" scripts, and the rest afterwards (makes the site look kinda-like it should before accessing elements through querySelector).

Gaben
  • 345
  • 1
  • 12
  • I’m gonna try this out today. Will let you know how this works in my use case. Fingers crossed!!!! – lopezdp Feb 07 '20 at 14:34
1

Looked through the answers and the most obvious and straight forward is missing: use document.write() to write out a chunk of CSS you need.

Here is an example (view it on codepen: http://codepen.io/ssh33/pen/zGjWga):

<style>
   @import url(http://fonts.googleapis.com/css?family=Open+Sans:800);
   .d, body{ font: 3vw 'Open Sans'; padding-top: 1em; }
   .d {
       text-align: center; background: #aaf;
       margin: auto; color: #fff; overflow: hidden; 
       width: 12em; height: 5em;
   }
</style>

<script>
   function w(s){document.write(s)}
   w("<style>.long-shadow { text-shadow: ");
   for(var i=0; i<449; i++) {
      if(i!= 0) w(","); w(i+"px "+i+"px #444");
   }
   w(";}</style>");
</script> 

<div class="d">
    <div class="long-shadow">Long Shadow<br> Short Code</div>
</div>
Stack
  • 348
  • 3
  • 17
1

For the benefit of searchers; if you are using jQuery, you can do the following:

var currentOverride = $('#customoverridestyles');

if (currentOverride) {
 currentOverride.remove();
}

$('body').append("<style id=\"customoverridestyles\">body{background-color:pink;}</style>");

Obviously you can change the inner css to whatever you want.

Appreciate some people prefer pure JavaScript, but it works and has been pretty robust for writing/overwriting styles dynamically.

JsAndDotNet
  • 16,260
  • 18
  • 100
  • 123
1
function createCSSClass(selector, style, hoverstyle) 
{
    if (!document.styleSheets) 
    {
        return;
    }

    if (document.getElementsByTagName("head").length == 0) 
    {

        return;
    }
    var stylesheet;
    var mediaType;
    if (document.styleSheets.length > 0) 
    {
        for (i = 0; i < document.styleSheets.length; i++) 
        {
            if (document.styleSheets[i].disabled) 
            {
                continue;
            }
            var media = document.styleSheets[i].media;
            mediaType = typeof media;

            if (mediaType == "string") 
            {
                if (media == "" || (media.indexOf("screen") != -1)) 
                {
                    styleSheet = document.styleSheets[i];
                }
            } 
            else if (mediaType == "object") 
            {
                if (media.mediaText == "" || (media.mediaText.indexOf("screen") != -1)) 
                {
                    styleSheet = document.styleSheets[i];
                }
            }

            if (typeof styleSheet != "undefined") 
            {
                break;
            }
        }
    }

    if (typeof styleSheet == "undefined") {
        var styleSheetElement = document.createElement("style");
        styleSheetElement.type = "text/css";
        document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
        for (i = 0; i < document.styleSheets.length; i++) {
            if (document.styleSheets[i].disabled) {
                continue;
            }
            styleSheet = document.styleSheets[i];
        }

        var media = styleSheet.media;
        mediaType = typeof media;
    }

    if (mediaType == "string") {
        for (i = 0; i < styleSheet.rules.length; i++) 
        {
            if (styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase()) 
            {
                styleSheet.rules[i].style.cssText = style;
                return;
            }
        }

        styleSheet.addRule(selector, style);
    }
    else if (mediaType == "object") 
    {
        for (i = 0; i < styleSheet.cssRules.length; i++) 
        {
            if (styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) 
            {
                styleSheet.cssRules[i].style.cssText = style;
                return;
            }
        }

        if (hoverstyle != null) 
        {
            styleSheet.insertRule(selector + "{" + style + "}", 0);
            styleSheet.insertRule(selector + ":hover{" + hoverstyle + "}", 1);
        }
        else 
        {
            styleSheet.insertRule(selector + "{" + style + "}", 0);
        }
    }
}





createCSSClass(".modalPopup  .header",
                                 " background-color: " + lightest + ";" +
                                  "height: 10%;" +
                                  "color: White;" +
                                  "line-height: 30px;" +
                                  "text-align: center;" +
                                  " width: 100%;" +
                                  "font-weight: bold; ", null);
tushar
  • 11
  • 1
0

This is what worked for me in Angular: In HTML I have button with programmatically created CSS with specific ID:

    <button [id]="'hoverbutton1'+item.key" [ngClass]="getHoverButtonClass()">
        <mat-icon class="icon">open_in_new</mat-icon>
    </button>

In typescript I created CSS and assign it to specific element with given ID:

addClasses(){
  var style1 = document.createElement('style');
  style1.innerHTML = '.hoverbutton'+this.item.key+' { display: none; }';
  document.getElementsByTagName('head')[0].appendChild(style1);
}

getHoverButtonClass() {
  return "hoverbutton"+this.item.key
}

This way I can create as many CSS classes as I want and assign them to elements individually. :)