Reputation: 287
Is it possible to hide style attribute in html so it still works? I mean this:
<html style="--color:#1E90FF;">
When I remove an attribut via removeAttr, it does not work at all. I can not do this via CSS this way:
:root {
--color: dodgerblue;
}
since the value is inserted through localStorage based on value. Is there any way to paste it into :root with jquery without creating this style attribute? Any ideas?
Upvotes: 0
Views: 307
Reputation: 598
If you have a "style" tag into your page, you can insert a CSS rule in it with "insertRule":
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule
document.getElementsByTagName('style')[0].sheet.insertRule(":root { --color: dodgerblue; }");
You can also create a tag in which you insert the rule:
document.getElementById('trigger').addEventListener('click', function() {
if (!document.getElementById('myCustomStyle')) {
var styleTag = document.createElement('style');
styleTag.id = 'myCustomStyle';
document.head.appendChild(styleTag);
styleTag.sheet.insertRule(":root { --color: dodgerblue; }");
styleTag.sheet.insertRule("p { color: var(--color); }");
}
});
<p>Click the button to insert CSS rules.</p>
<button id="trigger">INSERT</button>
Hope this helps!
Upvotes: 2