how to change a css value with javascript code example

Example 1: how to change css variable in javascript

document.documentElement.setAttribute("style", "--main-background-color: green");

Example 2: how to change style of an element using javascript

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Example 3: change css variable with javascript

let root = document.documentElement;

root.addEventListener("mousemove", e => {
  root.style.setProperty('--mouse-x', e.clientX + "px");
  root.style.setProperty('--mouse-y', e.clientY + "px");
});

Example 4: how to change css using javascript

document.getElementById("myText").className = "anyNewClass"

Tags:

Css Example