How do I edit a CSS variable using JS?











up vote
22
down vote

favorite
6












I have these CSS variables to control the colors of my project so I can do theming.



html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}


However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.



function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}


the error message










share|improve this question
























  • I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
    – ochi
    Dec 28 '16 at 22:43










  • No it is a css variable. I found out about them in this article
    – David Richards
    Dec 28 '16 at 22:44










  • broken-links.com/2014/08/28/…
    – David Richards
    Dec 28 '16 at 22:44






  • 2




    Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
    – ochi
    Dec 28 '16 at 22:54










  • I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
    – David Richards
    Dec 28 '16 at 23:12















up vote
22
down vote

favorite
6












I have these CSS variables to control the colors of my project so I can do theming.



html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}


However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.



function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}


the error message










share|improve this question
























  • I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
    – ochi
    Dec 28 '16 at 22:43










  • No it is a css variable. I found out about them in this article
    – David Richards
    Dec 28 '16 at 22:44










  • broken-links.com/2014/08/28/…
    – David Richards
    Dec 28 '16 at 22:44






  • 2




    Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
    – ochi
    Dec 28 '16 at 22:54










  • I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
    – David Richards
    Dec 28 '16 at 23:12













up vote
22
down vote

favorite
6









up vote
22
down vote

favorite
6






6





I have these CSS variables to control the colors of my project so I can do theming.



html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}


However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.



function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}


the error message










share|improve this question















I have these CSS variables to control the colors of my project so I can do theming.



html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}


However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.



function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}


the error message







javascript jquery css






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '16 at 23:22









Brett DeWoody

28.8k1885127




28.8k1885127










asked Dec 28 '16 at 22:40









David Richards

140137




140137












  • I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
    – ochi
    Dec 28 '16 at 22:43










  • No it is a css variable. I found out about them in this article
    – David Richards
    Dec 28 '16 at 22:44










  • broken-links.com/2014/08/28/…
    – David Richards
    Dec 28 '16 at 22:44






  • 2




    Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
    – ochi
    Dec 28 '16 at 22:54










  • I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
    – David Richards
    Dec 28 '16 at 23:12


















  • I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
    – ochi
    Dec 28 '16 at 22:43










  • No it is a css variable. I found out about them in this article
    – David Richards
    Dec 28 '16 at 22:44










  • broken-links.com/2014/08/28/…
    – David Richards
    Dec 28 '16 at 22:44






  • 2




    Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
    – ochi
    Dec 28 '16 at 22:54










  • I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
    – David Richards
    Dec 28 '16 at 23:12
















I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
– ochi
Dec 28 '16 at 22:43




I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
– ochi
Dec 28 '16 at 22:43












No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44




No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44












broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44




broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44




2




2




Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54




Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54












I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12




I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12












6 Answers
6






active

oldest

votes

















up vote
16
down vote



accepted










Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:



var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";


or



var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");


or



var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");


Demo



The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.






window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};

html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}

body {
background-color: var(--main-background-color);
}





This will only work in browsers supporting CSS variables obviously.






share|improve this answer



















  • 4




    This will overwrite the existing inline styles.
    – Oriol
    Dec 28 '16 at 23:30










  • yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
    – SuperUberDuper
    Mar 19 at 22:19


















up vote
12
down vote













If you are using :root:



:root {
--somevar: black;
}


It will be documentElement.



document.documentElement.style.setProperty('--somevar', 'green');





share|improve this answer




























    up vote
    10
    down vote













    You can simply use the standard way of setting arbitrary CSS properties: setProperty






    document.body.style.setProperty('--background-color', 'blue');

    body {
    --background-color: red;
    background-color: var(--background-color);
    }








    share|improve this answer





















    • for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
      – SuperUberDuper
      Mar 19 at 22:20


















    up vote
    6
    down vote













    The native solution



    The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().



    If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.



    // setter
    document.documentElement.style.setProperty('--myVariable', 'blue');
    // getter
    document.documentElement.style.getPropertyValue('--myVariable');


    However the getter will only return the value of a var, if has been set, using .setProperty().
    If has been set through CSS declaration, will return undefined. Check it in this example:






    let c = document.documentElement.style.getPropertyValue('--myVariable');
    alert('The value of --myVariable is : ' + (c?c:'undefined'));

    :root{ --myVariable : red; }
    div{ background-color: var(--myVariable); }

      <div>Red background set by --myVariable</div>





    To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
    The getter will then , look lik this :



    getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');


    In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...





    My personal approach



    I've implemented CSSGlobalVariablesa tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.



    // set a new value to --myVariable
    cssVar.myVariable = 'red';
    // get the value of --myVariable
    console.log( cssVar.myVariable );


    Any change applied to the Object properties, is translated automatically to the CSS variables.



    Available in : https://github.com/colxi/css-global-variables






    share|improve this answer






























      up vote
      1
      down vote













      You could add something like below (without using class variables)






      function loadTheme() {
      var htmlTag = document.getElementById("myDiv");
      var yourSelect = document.getElementById("themeSelect");
      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
      console.log("selected theme: " + selectedTheme);

      // reset class names
      htmlTag.className = '';
      // add selected theme
      htmlTag.className = 'theme' + selectedTheme;
      }

      .theme1 {
      color: blue;
      }
      .theme2 {
      color: red;
      }

      <div id="myDiv">
      test
      </div>
      <select id="themeSelect" onChange="loadTheme()">
      <option value="1">Theme 1</option>
      <option value="2">Theme 2</option>
      </select>








      share|improve this answer























      • Downvoted because it doesn't answer the question at all.
        – Ced
        Jun 3 '17 at 17:34










      • @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
        – ochi
        Jun 3 '17 at 20:11








      • 1




        changed my vote
        – Ced
        Jun 3 '17 at 20:26


















      up vote
      0
      down vote













      It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.






      share|improve this answer

















      • 2




        This is more of a comment than an answer
        – ochi
        Dec 28 '16 at 23:01










      • I didn't think about that. I'll give that a shot and get back to you
        – David Richards
        Dec 28 '16 at 23:10











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41370741%2fhow-do-i-edit-a-css-variable-using-js%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      16
      down vote



      accepted










      Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:



      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";


      or



      var html = document.getElementsByTagName('html')[0];
      html.style.setProperty("--main-background-color", "green");


      or



      var html = document.getElementsByTagName('html')[0];
      html.setAttribute("style", "--main-background-color: green");


      Demo



      The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.






      window.onload = function() {
      setTimeout(function() {
      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";
      }, 2000);
      };

      html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
      }

      body {
      background-color: var(--main-background-color);
      }





      This will only work in browsers supporting CSS variables obviously.






      share|improve this answer



















      • 4




        This will overwrite the existing inline styles.
        – Oriol
        Dec 28 '16 at 23:30










      • yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
        – SuperUberDuper
        Mar 19 at 22:19















      up vote
      16
      down vote



      accepted










      Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:



      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";


      or



      var html = document.getElementsByTagName('html')[0];
      html.style.setProperty("--main-background-color", "green");


      or



      var html = document.getElementsByTagName('html')[0];
      html.setAttribute("style", "--main-background-color: green");


      Demo



      The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.






      window.onload = function() {
      setTimeout(function() {
      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";
      }, 2000);
      };

      html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
      }

      body {
      background-color: var(--main-background-color);
      }





      This will only work in browsers supporting CSS variables obviously.






      share|improve this answer



















      • 4




        This will overwrite the existing inline styles.
        – Oriol
        Dec 28 '16 at 23:30










      • yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
        – SuperUberDuper
        Mar 19 at 22:19













      up vote
      16
      down vote



      accepted







      up vote
      16
      down vote



      accepted






      Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:



      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";


      or



      var html = document.getElementsByTagName('html')[0];
      html.style.setProperty("--main-background-color", "green");


      or



      var html = document.getElementsByTagName('html')[0];
      html.setAttribute("style", "--main-background-color: green");


      Demo



      The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.






      window.onload = function() {
      setTimeout(function() {
      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";
      }, 2000);
      };

      html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
      }

      body {
      background-color: var(--main-background-color);
      }





      This will only work in browsers supporting CSS variables obviously.






      share|improve this answer














      Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:



      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";


      or



      var html = document.getElementsByTagName('html')[0];
      html.style.setProperty("--main-background-color", "green");


      or



      var html = document.getElementsByTagName('html')[0];
      html.setAttribute("style", "--main-background-color: green");


      Demo



      The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.






      window.onload = function() {
      setTimeout(function() {
      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";
      }, 2000);
      };

      html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
      }

      body {
      background-color: var(--main-background-color);
      }





      This will only work in browsers supporting CSS variables obviously.






      window.onload = function() {
      setTimeout(function() {
      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";
      }, 2000);
      };

      html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
      }

      body {
      background-color: var(--main-background-color);
      }





      window.onload = function() {
      setTimeout(function() {
      var html = document.getElementsByTagName('html')[0];
      html.style.cssText = "--main-background-color: red";
      }, 2000);
      };

      html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
      }

      body {
      background-color: var(--main-background-color);
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jul 27 at 10:51

























      answered Dec 28 '16 at 23:16









      Brett DeWoody

      28.8k1885127




      28.8k1885127








      • 4




        This will overwrite the existing inline styles.
        – Oriol
        Dec 28 '16 at 23:30










      • yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
        – SuperUberDuper
        Mar 19 at 22:19














      • 4




        This will overwrite the existing inline styles.
        – Oriol
        Dec 28 '16 at 23:30










      • yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
        – SuperUberDuper
        Mar 19 at 22:19








      4




      4




      This will overwrite the existing inline styles.
      – Oriol
      Dec 28 '16 at 23:30




      This will overwrite the existing inline styles.
      – Oriol
      Dec 28 '16 at 23:30












      yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
      – SuperUberDuper
      Mar 19 at 22:19




      yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
      – SuperUberDuper
      Mar 19 at 22:19












      up vote
      12
      down vote













      If you are using :root:



      :root {
      --somevar: black;
      }


      It will be documentElement.



      document.documentElement.style.setProperty('--somevar', 'green');





      share|improve this answer

























        up vote
        12
        down vote













        If you are using :root:



        :root {
        --somevar: black;
        }


        It will be documentElement.



        document.documentElement.style.setProperty('--somevar', 'green');





        share|improve this answer























          up vote
          12
          down vote










          up vote
          12
          down vote









          If you are using :root:



          :root {
          --somevar: black;
          }


          It will be documentElement.



          document.documentElement.style.setProperty('--somevar', 'green');





          share|improve this answer












          If you are using :root:



          :root {
          --somevar: black;
          }


          It will be documentElement.



          document.documentElement.style.setProperty('--somevar', 'green');






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 '17 at 6:08









          Blauhirn

          4,84822964




          4,84822964






















              up vote
              10
              down vote













              You can simply use the standard way of setting arbitrary CSS properties: setProperty






              document.body.style.setProperty('--background-color', 'blue');

              body {
              --background-color: red;
              background-color: var(--background-color);
              }








              share|improve this answer





















              • for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
                – SuperUberDuper
                Mar 19 at 22:20















              up vote
              10
              down vote













              You can simply use the standard way of setting arbitrary CSS properties: setProperty






              document.body.style.setProperty('--background-color', 'blue');

              body {
              --background-color: red;
              background-color: var(--background-color);
              }








              share|improve this answer





















              • for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
                – SuperUberDuper
                Mar 19 at 22:20













              up vote
              10
              down vote










              up vote
              10
              down vote









              You can simply use the standard way of setting arbitrary CSS properties: setProperty






              document.body.style.setProperty('--background-color', 'blue');

              body {
              --background-color: red;
              background-color: var(--background-color);
              }








              share|improve this answer












              You can simply use the standard way of setting arbitrary CSS properties: setProperty






              document.body.style.setProperty('--background-color', 'blue');

              body {
              --background-color: red;
              background-color: var(--background-color);
              }








              document.body.style.setProperty('--background-color', 'blue');

              body {
              --background-color: red;
              background-color: var(--background-color);
              }





              document.body.style.setProperty('--background-color', 'blue');

              body {
              --background-color: red;
              background-color: var(--background-color);
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 28 '16 at 23:27









              Oriol

              153k33252353




              153k33252353












              • for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
                – SuperUberDuper
                Mar 19 at 22:20


















              • for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
                – SuperUberDuper
                Mar 19 at 22:20
















              for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
              – SuperUberDuper
              Mar 19 at 22:20




              for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
              – SuperUberDuper
              Mar 19 at 22:20










              up vote
              6
              down vote













              The native solution



              The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().



              If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.



              // setter
              document.documentElement.style.setProperty('--myVariable', 'blue');
              // getter
              document.documentElement.style.getPropertyValue('--myVariable');


              However the getter will only return the value of a var, if has been set, using .setProperty().
              If has been set through CSS declaration, will return undefined. Check it in this example:






              let c = document.documentElement.style.getPropertyValue('--myVariable');
              alert('The value of --myVariable is : ' + (c?c:'undefined'));

              :root{ --myVariable : red; }
              div{ background-color: var(--myVariable); }

                <div>Red background set by --myVariable</div>





              To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
              The getter will then , look lik this :



              getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');


              In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...





              My personal approach



              I've implemented CSSGlobalVariablesa tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.



              // set a new value to --myVariable
              cssVar.myVariable = 'red';
              // get the value of --myVariable
              console.log( cssVar.myVariable );


              Any change applied to the Object properties, is translated automatically to the CSS variables.



              Available in : https://github.com/colxi/css-global-variables






              share|improve this answer



























                up vote
                6
                down vote













                The native solution



                The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().



                If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.



                // setter
                document.documentElement.style.setProperty('--myVariable', 'blue');
                // getter
                document.documentElement.style.getPropertyValue('--myVariable');


                However the getter will only return the value of a var, if has been set, using .setProperty().
                If has been set through CSS declaration, will return undefined. Check it in this example:






                let c = document.documentElement.style.getPropertyValue('--myVariable');
                alert('The value of --myVariable is : ' + (c?c:'undefined'));

                :root{ --myVariable : red; }
                div{ background-color: var(--myVariable); }

                  <div>Red background set by --myVariable</div>





                To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
                The getter will then , look lik this :



                getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');


                In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...





                My personal approach



                I've implemented CSSGlobalVariablesa tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.



                // set a new value to --myVariable
                cssVar.myVariable = 'red';
                // get the value of --myVariable
                console.log( cssVar.myVariable );


                Any change applied to the Object properties, is translated automatically to the CSS variables.



                Available in : https://github.com/colxi/css-global-variables






                share|improve this answer

























                  up vote
                  6
                  down vote










                  up vote
                  6
                  down vote









                  The native solution



                  The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().



                  If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.



                  // setter
                  document.documentElement.style.setProperty('--myVariable', 'blue');
                  // getter
                  document.documentElement.style.getPropertyValue('--myVariable');


                  However the getter will only return the value of a var, if has been set, using .setProperty().
                  If has been set through CSS declaration, will return undefined. Check it in this example:






                  let c = document.documentElement.style.getPropertyValue('--myVariable');
                  alert('The value of --myVariable is : ' + (c?c:'undefined'));

                  :root{ --myVariable : red; }
                  div{ background-color: var(--myVariable); }

                    <div>Red background set by --myVariable</div>





                  To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
                  The getter will then , look lik this :



                  getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');


                  In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...





                  My personal approach



                  I've implemented CSSGlobalVariablesa tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.



                  // set a new value to --myVariable
                  cssVar.myVariable = 'red';
                  // get the value of --myVariable
                  console.log( cssVar.myVariable );


                  Any change applied to the Object properties, is translated automatically to the CSS variables.



                  Available in : https://github.com/colxi/css-global-variables






                  share|improve this answer














                  The native solution



                  The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().



                  If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.



                  // setter
                  document.documentElement.style.setProperty('--myVariable', 'blue');
                  // getter
                  document.documentElement.style.getPropertyValue('--myVariable');


                  However the getter will only return the value of a var, if has been set, using .setProperty().
                  If has been set through CSS declaration, will return undefined. Check it in this example:






                  let c = document.documentElement.style.getPropertyValue('--myVariable');
                  alert('The value of --myVariable is : ' + (c?c:'undefined'));

                  :root{ --myVariable : red; }
                  div{ background-color: var(--myVariable); }

                    <div>Red background set by --myVariable</div>





                  To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
                  The getter will then , look lik this :



                  getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');


                  In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...





                  My personal approach



                  I've implemented CSSGlobalVariablesa tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.



                  // set a new value to --myVariable
                  cssVar.myVariable = 'red';
                  // get the value of --myVariable
                  console.log( cssVar.myVariable );


                  Any change applied to the Object properties, is translated automatically to the CSS variables.



                  Available in : https://github.com/colxi/css-global-variables






                  let c = document.documentElement.style.getPropertyValue('--myVariable');
                  alert('The value of --myVariable is : ' + (c?c:'undefined'));

                  :root{ --myVariable : red; }
                  div{ background-color: var(--myVariable); }

                    <div>Red background set by --myVariable</div>





                  let c = document.documentElement.style.getPropertyValue('--myVariable');
                  alert('The value of --myVariable is : ' + (c?c:'undefined'));

                  :root{ --myVariable : red; }
                  div{ background-color: var(--myVariable); }

                    <div>Red background set by --myVariable</div>






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 24 at 1:03

























                  answered Mar 20 at 5:38









                  colxi

                  2,0081726




                  2,0081726






















                      up vote
                      1
                      down vote













                      You could add something like below (without using class variables)






                      function loadTheme() {
                      var htmlTag = document.getElementById("myDiv");
                      var yourSelect = document.getElementById("themeSelect");
                      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
                      console.log("selected theme: " + selectedTheme);

                      // reset class names
                      htmlTag.className = '';
                      // add selected theme
                      htmlTag.className = 'theme' + selectedTheme;
                      }

                      .theme1 {
                      color: blue;
                      }
                      .theme2 {
                      color: red;
                      }

                      <div id="myDiv">
                      test
                      </div>
                      <select id="themeSelect" onChange="loadTheme()">
                      <option value="1">Theme 1</option>
                      <option value="2">Theme 2</option>
                      </select>








                      share|improve this answer























                      • Downvoted because it doesn't answer the question at all.
                        – Ced
                        Jun 3 '17 at 17:34










                      • @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
                        – ochi
                        Jun 3 '17 at 20:11








                      • 1




                        changed my vote
                        – Ced
                        Jun 3 '17 at 20:26















                      up vote
                      1
                      down vote













                      You could add something like below (without using class variables)






                      function loadTheme() {
                      var htmlTag = document.getElementById("myDiv");
                      var yourSelect = document.getElementById("themeSelect");
                      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
                      console.log("selected theme: " + selectedTheme);

                      // reset class names
                      htmlTag.className = '';
                      // add selected theme
                      htmlTag.className = 'theme' + selectedTheme;
                      }

                      .theme1 {
                      color: blue;
                      }
                      .theme2 {
                      color: red;
                      }

                      <div id="myDiv">
                      test
                      </div>
                      <select id="themeSelect" onChange="loadTheme()">
                      <option value="1">Theme 1</option>
                      <option value="2">Theme 2</option>
                      </select>








                      share|improve this answer























                      • Downvoted because it doesn't answer the question at all.
                        – Ced
                        Jun 3 '17 at 17:34










                      • @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
                        – ochi
                        Jun 3 '17 at 20:11








                      • 1




                        changed my vote
                        – Ced
                        Jun 3 '17 at 20:26













                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      You could add something like below (without using class variables)






                      function loadTheme() {
                      var htmlTag = document.getElementById("myDiv");
                      var yourSelect = document.getElementById("themeSelect");
                      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
                      console.log("selected theme: " + selectedTheme);

                      // reset class names
                      htmlTag.className = '';
                      // add selected theme
                      htmlTag.className = 'theme' + selectedTheme;
                      }

                      .theme1 {
                      color: blue;
                      }
                      .theme2 {
                      color: red;
                      }

                      <div id="myDiv">
                      test
                      </div>
                      <select id="themeSelect" onChange="loadTheme()">
                      <option value="1">Theme 1</option>
                      <option value="2">Theme 2</option>
                      </select>








                      share|improve this answer














                      You could add something like below (without using class variables)






                      function loadTheme() {
                      var htmlTag = document.getElementById("myDiv");
                      var yourSelect = document.getElementById("themeSelect");
                      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
                      console.log("selected theme: " + selectedTheme);

                      // reset class names
                      htmlTag.className = '';
                      // add selected theme
                      htmlTag.className = 'theme' + selectedTheme;
                      }

                      .theme1 {
                      color: blue;
                      }
                      .theme2 {
                      color: red;
                      }

                      <div id="myDiv">
                      test
                      </div>
                      <select id="themeSelect" onChange="loadTheme()">
                      <option value="1">Theme 1</option>
                      <option value="2">Theme 2</option>
                      </select>








                      function loadTheme() {
                      var htmlTag = document.getElementById("myDiv");
                      var yourSelect = document.getElementById("themeSelect");
                      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
                      console.log("selected theme: " + selectedTheme);

                      // reset class names
                      htmlTag.className = '';
                      // add selected theme
                      htmlTag.className = 'theme' + selectedTheme;
                      }

                      .theme1 {
                      color: blue;
                      }
                      .theme2 {
                      color: red;
                      }

                      <div id="myDiv">
                      test
                      </div>
                      <select id="themeSelect" onChange="loadTheme()">
                      <option value="1">Theme 1</option>
                      <option value="2">Theme 2</option>
                      </select>





                      function loadTheme() {
                      var htmlTag = document.getElementById("myDiv");
                      var yourSelect = document.getElementById("themeSelect");
                      var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
                      console.log("selected theme: " + selectedTheme);

                      // reset class names
                      htmlTag.className = '';
                      // add selected theme
                      htmlTag.className = 'theme' + selectedTheme;
                      }

                      .theme1 {
                      color: blue;
                      }
                      .theme2 {
                      color: red;
                      }

                      <div id="myDiv">
                      test
                      </div>
                      <select id="themeSelect" onChange="loadTheme()">
                      <option value="1">Theme 1</option>
                      <option value="2">Theme 2</option>
                      </select>






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jun 3 '17 at 20:26









                      Ced

                      6,68313881




                      6,68313881










                      answered Dec 28 '16 at 23:22









                      ochi

                      8,59843247




                      8,59843247












                      • Downvoted because it doesn't answer the question at all.
                        – Ced
                        Jun 3 '17 at 17:34










                      • @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
                        – ochi
                        Jun 3 '17 at 20:11








                      • 1




                        changed my vote
                        – Ced
                        Jun 3 '17 at 20:26


















                      • Downvoted because it doesn't answer the question at all.
                        – Ced
                        Jun 3 '17 at 17:34










                      • @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
                        – ochi
                        Jun 3 '17 at 20:11








                      • 1




                        changed my vote
                        – Ced
                        Jun 3 '17 at 20:26
















                      Downvoted because it doesn't answer the question at all.
                      – Ced
                      Jun 3 '17 at 17:34




                      Downvoted because it doesn't answer the question at all.
                      – Ced
                      Jun 3 '17 at 17:34












                      @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
                      – ochi
                      Jun 3 '17 at 20:11






                      @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
                      – ochi
                      Jun 3 '17 at 20:11






                      1




                      1




                      changed my vote
                      – Ced
                      Jun 3 '17 at 20:26




                      changed my vote
                      – Ced
                      Jun 3 '17 at 20:26










                      up vote
                      0
                      down vote













                      It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.






                      share|improve this answer

















                      • 2




                        This is more of a comment than an answer
                        – ochi
                        Dec 28 '16 at 23:01










                      • I didn't think about that. I'll give that a shot and get back to you
                        – David Richards
                        Dec 28 '16 at 23:10















                      up vote
                      0
                      down vote













                      It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.






                      share|improve this answer

















                      • 2




                        This is more of a comment than an answer
                        – ochi
                        Dec 28 '16 at 23:01










                      • I didn't think about that. I'll give that a shot and get back to you
                        – David Richards
                        Dec 28 '16 at 23:10













                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.






                      share|improve this answer












                      It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}, .theme2 {...}, etc) and then change the class with JS based on the selected value.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 28 '16 at 22:59









                      johnniebenson

                      47039




                      47039








                      • 2




                        This is more of a comment than an answer
                        – ochi
                        Dec 28 '16 at 23:01










                      • I didn't think about that. I'll give that a shot and get back to you
                        – David Richards
                        Dec 28 '16 at 23:10














                      • 2




                        This is more of a comment than an answer
                        – ochi
                        Dec 28 '16 at 23:01










                      • I didn't think about that. I'll give that a shot and get back to you
                        – David Richards
                        Dec 28 '16 at 23:10








                      2




                      2




                      This is more of a comment than an answer
                      – ochi
                      Dec 28 '16 at 23:01




                      This is more of a comment than an answer
                      – ochi
                      Dec 28 '16 at 23:01












                      I didn't think about that. I'll give that a shot and get back to you
                      – David Richards
                      Dec 28 '16 at 23:10




                      I didn't think about that. I'll give that a shot and get back to you
                      – David Richards
                      Dec 28 '16 at 23:10


















                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41370741%2fhow-do-i-edit-a-css-variable-using-js%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Berounka

                      Sphinx de Gizeh

                      Different font size/position of beamer's navigation symbols template's content depending on regular/plain...