I'm trying to use the browser's built in type CSSStyleDeclaration
to programatically pass around and modify styles (which is handy because of the .cssText
property).
However, new CSSStyleDeclaration()
throws an Illegal Constructor
error. So I tried Object.create(CSSStyleDeclaration.prototype)
, which appears to work, but the resulting object doesn't behave normally. For example, calling .cssText
on a CSSStyleDeclaration
created this way throws an Illegal invocation
.
Is there a "right" way to construct CSSStyleDeclaration
? Or is there a better way to create styles programmatically using the built-in types?
(I don't want to do string manipulation and I'd rather avoid making my own types or adding a 3rd party dependency.)
you may create a temporary DOM element and use its style
property:
const rules = document.createElement('span').style;
rules.backgroundColor = 'red';
rules.cursor = 'pointer';
rules.color = 'white';
document.getElementById('style_string').innerHTML = rules.cssText;
document.getElementById('obj').style = rules.cssText;
<pre id="style_string"></pre>
<div id="obj">TEST</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With