Home >Web Front-end >CSS Tutorial >How Do I Access CSS Variables Using JavaScript?
How to Access CSS Variables in JavaScript
Accessing CSS variables from JavaScript enables you to dynamically manipulate the styling of your web application. Here's how you can achieve this:
Step 1: Get Computed Styles
Use the getComputedStyle function to retrieve the computed styles of the target element.
Step 2: Get Property Value
Utilize the getPropertyValue method to fetch the value of the desired CSS variable.
Syntax:
getComputedStyle(element).getPropertyValue('--variable-name');
Example:
To retrieve the value of the --color-font-general CSS variable declared in the provided code snippet:
var style = getComputedStyle(document.body); var color = style.getPropertyValue('--color-font-general');
This code will capture the value of the CSS variable and store it in the color variable.
The above is the detailed content of How Do I Access CSS Variables Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!