May 2, 2012

How to dynamically set and modify CSS in JavaScript?

Question by AkademiksQc

I have some JavaScript code that creates some div elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css file, I would like to set the CSS className of my element and then dynamically inject some values into the defined CSS property.

Here is what I would like to do :

style.css:

.myClass { 
    width: $insertedFromJS 
}

script.js:

var myElement = document.createElement("div");
myElement.className = "myClass";

I want to do something like this but at that point myElement.style.width is empty

myElement.style.width.replaceAll("$insertedFromJS", "400px");

I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.

Answer by Mark Rawlingson

If I understand your question properly, it sounds like you’re trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can’t do that in the way you’re trying to do it. In order to do that, you’d have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that’s a really overly-complicated way to go about doing something that…

myElement.style.width = "400px";

…can do for you in a couple of seconds. I know it doesn’t really address the issue of decoupling css from js, but there’s not really a whole lot you can do about that. You’re trying to set css dynamically, after all.

Depending on what you’re trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.

Answer by Starx

Setting the style, might be accomplished defining the inner-page style declaration.

Here is what i mean

var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';

However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.

if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules)  // Standards Compliant {
   csses = document.styleSheets[0].cssRules;
}
else {         
   csses = document.styleSheets[0].rules;  // IE 
}
for (i=0;i<csses.length;i++) {
   if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
   {
     thecss[i].style.cssText="color:#000";
   }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!