Skip to main content

Assign Js to Css

Assigning JavaScript Variables for Use in CSS

Way 1: Native DOM Methods

Using native DOM methods to modify CSS styles, for example:

1document.getElementById(id).style.property = new style();

Within this new style block, you can utilize variables passed in from JavaScript.

While this approach certainly works, it becomes rather cumbersome when dealing with more complex CSS modifications—such as animations. In such scenarios, the method described below proves to be far more essential.


Way 2: CSS Variable

The approach involves utilizing CSS variables: assign the value of a JavaScript variable to a CSS variable, and then use that CSS variable within your CSS styles.

for example:

1// set variable
2document.body.style.setProperty("--primary", "#7F583F");
3// get variable
4document.body.style.getPropertyValue("--primary").trim();
5// '#7F583F'
6// remove variable
7document.body.style.removeProperty("--primary");
1/* Declaring CSS variables directly within the style block */
2body {
3	--foo: #7f583f;
4}
5.content {
6	--bar: #f7efd2;
7}