Home >Web Front-end >CSS Tutorial >How Can I Effectively Access and Modify CSS Custom Properties Using JavaScript?

How Can I Effectively Access and Modify CSS Custom Properties Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 09:41:10423browse

How Can I Effectively Access and Modify CSS Custom Properties Using JavaScript?

Interacting with CSS Custom Properties in JavaScript

In modern web development, CSS custom properties, also known as CSS variables, play a vital role in enhancing style customization and code maintainability. These properties can be defined within stylesheets and accessed using the var(...) syntax. However, accessing and manipulating them through JavaScript presents a unique challenge.

Custom Property Access and Manipulation

To access a CSS custom property using JavaScript, you can leverage the document.body.style.setProperty() method. This method accepts two arguments:

  • --name: The name of the custom property, prefixed with two dashes (--).
  • value: The value you want to assign to the property.

For example, to change the '--mycolor' custom property defined in the provided HTML code:

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

jQuery for Property Manipulation

Alternatively, you can use jQuery's css() method to achieve the same result:

$('body').css('--mycolor', 'red');

Example

In your provided HTML code, you were attempting to modify the '--mycolor' property using incorrect syntax. To achieve the desired effect, the following modifications are necessary:

function plain_js() { 
  document.body.style['font-weight'] = 'bold';
  document.body.style.setProperty('--mycolor', 'red');
}

function jQuery_() {
  $('body').css('font-weight', 'bold');
  $('body').css('--mycolor', 'red');
}

By using the appropriate syntax, you can now successfully set both the 'font-weight' property and the '--mycolor' custom property, dynamically changing the text and background color of the target element.

The above is the detailed content of How Can I Effectively Access and Modify CSS Custom Properties Using 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