Categories
JavaScript Answers

How to change CSS :root color variables in JavaScript?

Spread the love

You can change CSS :root color variables in JavaScript by accessing the document.documentElement.style object.

To do this we write:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change CSS :root Color Variables</title>
    <style>
        :root {
            --main-color: red;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: var(--main-color);
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <button onclick="changeColor()">Change Color</button>

    <script>
        function changeColor() {
            // Access the root element
            const root = document.documentElement;

            // Change the value of the --main-color variable
            root.style.setProperty('--main-color', 'blue');
        }
    </script>
</body>
</html>

In this example, the :root pseudo-class defines CSS variables.

We have a .box div with a background color set to the value of the --main-color variable.

When the button is clicked, the changeColor() function is called.

Inside the function, we access the root element (document.documentElement) and use the setProperty() method to change the value of the --main-color variable to 'blue'.

You can replace 'blue' with any color value you want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *