CodexBloom - Programming Q&A Platform

CSS Variables Not Updating After DOM Manipulation with Vanilla JS

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-10
css javascript variables JavaScript

I've been struggling with this for a few days now and could really use some help. I'm experiencing an issue where CSS variables defined in my stylesheet are not reflecting the changes I make to them using JavaScript. I'm using vanilla JavaScript and trying to update a CSS variable on a specific element after an event occurs. Here's a simplified version of my code: ```css :root { --main-bg-color: #fff; --main-text-color: #000; } .container { background-color: var(--main-bg-color); color: var(--main-text-color); } ``` ```html <div class="container"> <p>Hello World!</p> <button id="changeColor">Change Color</button> </div> ``` ```javascript document.getElementById('changeColor').addEventListener('click', function() { document.documentElement.style.setProperty('--main-bg-color', '#333'); document.documentElement.style.setProperty('--main-text-color', '#fff'); }); ``` When I click the button, I expect the background color of the `.container` to change to dark gray and the text color to change to white. However, nothing happens. I've checked that my event listener is firing correctly, and the new values are being set, but the visual changes are not reflecting on the page. I have also tried refreshing the page after making the changes, but that doesn't help either. Am I missing something in my approach, or is there a specific reason why the CSS variables aren't updating as expected? This is all happening in Chrome version 95.0.4638.69. I’ve tried checking for any conflicting styles in my CSS, and I confirmed that the variables are correctly defined in the `:root` selector. I also attempted to set the properties directly on the `.container` element instead of the `:root`, but that resulted in the same issue. Any insights would be greatly appreciated! For context: I'm using Javascript on Linux. What are your experiences with this?