Home >Web Front-end >CSS Tutorial >How Can I Access and Modify CSS Custom Properties (Variables) with JavaScript?

How Can I Access and Modify CSS Custom Properties (Variables) with JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 01:46:14386browse

How Can I Access and Modify CSS Custom Properties (Variables) with JavaScript?

Accessing CSS Custom Properties (Variables) via JavaScript

JavaScript provides the means to interact with CSS custom properties, known as CSS variables. Despite being defined as var() in stylesheets, accessing them through JavaScript requires a slightly different approach.

Getting and Setting Custom Properties

To get the value of a custom property, use the following syntax:

var value = document.body.style.getPropertyValue('--property-name');

Similarly, to set a custom property, use:

document.body.style.setProperty('--property-name', 'new-value');

Example Implementation

Consider a custom property --mycolor defined in CSS as the background color of an element. To change its color using JavaScript, you can execute the following code:

document.body.style.setProperty('--mycolor', 'red');

Alternative Methods

jQuery also offers methods for interacting with custom properties:

// Get property
var value = $('body').css('--property-name');

// Set property
$('body').css('--property-name', 'new-value');

Avoiding Common Pitfalls

As demonstrated in the initial example, accessing custom properties using the standard [style.property] syntax (e.g., document.body.style['--mycolor']) will not work. Instead, use the getPropertyValue and setProperty methods with a double hyphen before the property name.

The above is the detailed content of How Can I Access and Modify CSS Custom Properties (Variables) with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn