Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new CSSStyleDeclaration

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.)

like image 694
MgSam Avatar asked Jul 20 '18 17:07

MgSam


1 Answers

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>
like image 96
Roman86 Avatar answered Oct 10 '22 21:10

Roman86