JAVASCRIPT
Dynamically Update CSS Variables on an Element
Learn how to use JavaScript to dynamically set and update CSS custom properties (variables) on specific DOM elements, enabling powerful runtime styling and theming without class toggles.
function setElementCssVariable(elementId, variableName, value) {
const element = document.getElementById(elementId);
if (element) {
element.style.setProperty(`--${variableName}`, value);
console.log(`CSS variable --${variableName} set to ${value} on element ${elementId}`);
} else {
console.warn(`Element with ID '${elementId}' not found.`);
}
}
// Example Usage:
// Assuming you have an element like: <div id="myBox" style="--box-color: blue;"></div>
// And some CSS: #myBox { background-color: var(--box-color); width: 100px; height: 100px; }
// Set a custom CSS variable
setElementCssVariable('myBox', 'box-color', 'rebeccapurple');
// Change another variable (e.g., for size)
// setElementCssVariable('myBox', 'box-size', '150px');
// (requires --box-size to be used in CSS, e.g., width: var(--box-size);)
How it works: This snippet provides a utility function to programmatically update CSS custom properties (variables) on any given DOM element. By using `element.style.setProperty('--variable-name', value)`, you can manipulate an element's styles dynamically based on user interactions, data changes, or thematic shifts, without needing to add or remove CSS classes for every style variation. This is highly useful for creating flexible and customizable UI components.