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
Release: 2024-12-06 01:46:14
Original
390 people have browsed it

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');
Copy after login

Similarly, to set a custom property, use:

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

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');
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template