How to dynamically set and change CSS in JavaScript?

I have JavaScript code that creates some elements div, and it sets its CSS properties. Since I would like to separate CSS logic from JavaScript code and because CSS is easier to read in my own .cssfile, I would like to set the CSS of classNamemy element and then dynamically insert some values ​​into a specific 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 this point is myElement.style.widthempty

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

I think my problem here is that after calling myElement.className = "myClass"CSS, it still doesn't apply.

+3
source share
4 answers

, , - css, javascript css, . , . CSS dom, , DOM. -, ...

myElement.style.width = "400px";

... . , css js, . css , .

, , className js.

+2

.

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';

, . . , .

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";
   }
}
+1

Could you use jQuery? you can use

$(".class").css("property", val); /* or use the .width property */ 
0
source

There is a jQuery plugin called jQuery Rule, http://flesler.blogspot.com/2007/11/jqueryrule.html

I tried dynamically setting some div sizes in a board game. It works in FireFox, not in Chrome. I have not tried IE9.

-1
source

All Articles