JAVASCRIPT

Manipulate CSS Custom Properties with JavaScript

Dynamically change website themes or individual component styles by reading and updating CSS custom properties (variables) using JavaScript DOM methods.

// Assume CSS defines: :root { --primary-color: #007bff; --spacing-unit: 10px; }
// or .my-component { --component-bg: lightgray; }

// Get a CSS custom property from the root (global scope)
function getRootCssVar(varName) {
  return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
}

// Set a CSS custom property on the root (global scope)
function setRootCssVar(varName, value) {
  document.documentElement.style.setProperty(varName, value);
}

// Get a CSS custom property from a specific element
function getElementCssVar(element, varName) {
  return getComputedStyle(element).getPropertyValue(varName).trim();
}

// Set a CSS custom property on a specific element
function setElementCssVar(element, varName, value) {
  element.style.setProperty(varName, value);
}

// Example Usage:
// console.log('Current primary color:', getRootCssVar('--primary-color'));
// setRootCssVar('--primary-color', '#ff5733');
// console.log('New primary color:', getRootCssVar('--primary-color'));

// const myDiv = document.getElementById('myDiv');
// console.log('Div background:', getElementCssVar(myDiv, '--component-bg'));
// setElementCssVar(myDiv, '--component-bg', 'darkblue');
// HTML: <style>:root { --primary-color: #007bff; } #myDiv { --component-bg: lightgray; background: var(--component-bg); }</style>
// <div id="myDiv" style="width:100px;height:50px;margin:10px;"></div>
How it works: CSS Custom Properties (or CSS Variables) allow you to define reusable values throughout your stylesheets. JavaScript can interact with these variables using `getComputedStyle()` to read their current values and `element.style.setProperty()` to dynamically update them. This enables powerful runtime theme switching, responsive design adjustments, and dynamic styling based on user interaction without complex class manipulation or inline style overriding for every property.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs