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
Release: 2024-12-05 09:41:10
Original
427 people have browsed it

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

jQuery for Property Manipulation

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

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

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

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!

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