Sometimes, we want to change CSS values with JavaScript.
In this article, we’ll look at how to change CSS values with JavaScript.
How to change CSS values with JavaScript?
To change CSS values with JavaScript, we can get the rule from document.styleSheets and set the rule’s values.
For instance, we write
const cssRuleCode = document.all ? "rules" : "cssRules";
const rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
rule.selectorText = selector;
rule.value = value;
to get the rule we want to update with document.styleSheets[styleIndex][cssRuleCode][ruleIndex].
Then we set the selector text of the rule with
rule.selectorText = selector;
And we set the value of the rule with
rule.value = value;
Conclusion
To change CSS values with JavaScript, we can get the rule from document.styleSheets and set the rule’s values.