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 add a new stylesheet with the rules.
For instance, we write
const style = document.createElement("style");
document.head.appendChild(style);
stylesheet = style.sheet;
const css = (selector, property, value) => {
try {
stylesheet.insertRule(
selector + " {" + property + ":" + value + "}",
stylesheet.cssRules.length
);
} catch (err) {}
};
to create a new style element with createElement
.
Then we append it to the head element with document.head.appendChild
.
Then we get the style sheet with style.sheet
.,
Next, in the css
function, we call insertRule
to insert a new style rule into the stylesheet.
The first argument is the rule and the 2nd argument is the index of the rule.
Conclusion
To change CSS Values with JavaScript, we add a new stylesheet with the rules.