Updating a root css style through JavaScript


Basically I need to set theme color which is passed as a model attribute from my controller to my CSS file using JavaScript.

Here is the current CSS file root part:

:root {
    --clr-primary: #ffca00;
    --clr-dark-blue: #1d1836;
    /* --clr-accent: #4917D6; */
    --clr-black-900: #1f1f1f;
    --clr-black-800: #303030;
    --clr-black-600: #3f3f3f;
    --clr-white-off: #f7f7f7;

I need to update ‘–clr-primary’ to whatever theme color when the page loads.

So what I did was using JavaScript:

    var jsonThemeColor = $('#menuThemeColor').val();
    var themeColor = JSON.parse(jsonThemeColor)

Yet this doesn’t work. Mind you, I have a separate CSS file I have not included CSS inside a <style> tags. So there are no errors, it’s just that the color is not getting updated and instead it’s showing white color.


You can do something like,

document.documentElement.style.setProperty('--property', 'color');

You can visit this link for a demo created by wesbos.

Answered By – Md Sabbir Alam

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published