← Back to all snippets
JAVASCRIPT

Read and Modify CSS Custom Properties (Variables) with JavaScript

Dynamically update and retrieve CSS custom properties (variables) using JavaScript. This allows for powerful client-side theme switching, dynamic styling adjustments, and responsive designs.

/**
 * Reads a CSS custom property from an element or the document root.
 * @param {string} propertyName - The name of the custom property (e.g., '--primary-color').
 * @param {HTMLElement} [element=document.documentElement] - The element to read from. Defaults to document.documentElement (root).
 * @returns {string} The value of the custom property.
 */
function getCssVariable(propertyName, element = document.documentElement) {
  if (!propertyName.startsWith('--')) {
    propertyName = `--${propertyName}`; // Ensure it starts with --
  }
  return getComputedStyle(element).getPropertyValue(propertyName).trim();
}

/**
 * Sets a CSS custom property on an element or the document root.
 * @param {string} propertyName - The name of the custom property (e.g., '--primary-color').
 * @param {string} value - The new value for the custom property.
 * @param {HTMLElement} [element=document.documentElement] - The element to set the property on. Defaults to document.documentElement (root).
 */
function setCssVariable(propertyName, value, element = document.documentElement) {
  if (!propertyName.startsWith('--')) {
    propertyName = `--${propertyName}`; // Ensure it starts with --
  }
  element.style.setProperty(propertyName, value);
}

// Example Usage:
// In your CSS:
// :root {
//   --primary-color: #007bff;
//   --spacing-unit: 1rem;
// }
// .card {
//   --card-bg-color: lightgray;
//   background-color: var(--card-bg-color);
// }

// Read a global variable
// const primaryColor = getCssVariable('--primary-color');
// console.log('Current primary color:', primaryColor); // e.g., #007bff

// Set a global variable (e.g., for dark mode)
// setCssVariable('--primary-color', '#6f42c1'); // Changes primary color globally

// Read and set a local variable on a specific element
// const myCard = document.querySelector('.card');
// if (myCard) {
//   const cardBg = getCssVariable('--card-bg-color', myCard);
//   console.log('Card background color:', cardBg); // e.g., lightgray
//   setCssVariable('--card-bg-color', 'darkslategray', myCard);
// }
How it works: This snippet provides two utility functions to interact with CSS Custom Properties (CSS Variables) using JavaScript. `getCssVariable` allows you to retrieve the current computed value of a variable, while `setCssVariable` lets you dynamically update it. These functions default to operating on the document's root element (`document.documentElement`) for global variables but can also target specific elements for localized variable manipulation. This enables dynamic styling, theme switching, and responsive design adjustments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs