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.